express-typed-routes 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Thomas Pregenzer
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,177 @@
1
+ # express-typed-routes
2
+
3
+ Type-safe middleware composition for Express with full TypeScript support.
4
+
5
+ ## Features
6
+
7
+ - Type-safe middleware chaining with full TypeScript inference
8
+ - Works with your existing Express apps and middleware
9
+ - Errors automatically flow to Express error handlers
10
+ - Zero dependencies
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ npm install express-typed-routes
16
+ ```
17
+
18
+ ## Quick Start
19
+
20
+ ```typescript
21
+ import express from "express";
22
+ import { route, middleware } from "express-typed-routes";
23
+
24
+ const app = express();
25
+
26
+ // Create typed middleware
27
+ const requireAuth = middleware<{ userId: string }>((req) => {
28
+ const token = req.headers.authorization?.substring(7);
29
+ if (!token) throw new Error("Unauthorized");
30
+ return { userId: token };
31
+ });
32
+
33
+ // Use it in routes with full type safety
34
+ app.get(
35
+ "/api/profile",
36
+ route()
37
+ .use(requireAuth)
38
+ .handler((req, res) => {
39
+ // TypeScript knows req.userId exists and is a string!
40
+ res.json({ userId: req.userId });
41
+ })
42
+ );
43
+
44
+ app.listen(3000);
45
+ ```
46
+
47
+ ## Why?
48
+
49
+ Express middleware lose type information when applied to routes. `express-typed-routes` gives you full TypeScript inference for your request object.
50
+
51
+ **No more custom type definitions like:**
52
+ ```typescript
53
+ // types/express.d.ts
54
+ declare global {
55
+ namespace Express {
56
+ interface Request {
57
+ userId?: string;
58
+ }
59
+ }
60
+ }
61
+ ```
62
+
63
+ **With this library:**
64
+ ```typescript
65
+ app.get(
66
+ "/profile",
67
+ route()
68
+ .use(requireAuth)
69
+ .handler((req, res) => {
70
+ res.json({ userId: req.userId }); // ✅ TypeScript knows userId exists!
71
+ })
72
+ );
73
+ ```
74
+
75
+ ## Why I built this
76
+
77
+ I was building my first Express-based personal project and got frustrated having to override the Express Request type with optional fields for every middleware property. On top of that, I was using Zod and had to parse my schema manually in every single handler.
78
+
79
+ I figured there had to be a better way - so I built this. Let me know what you think.
80
+
81
+ ## More Examples
82
+
83
+ ### Chaining Multiple Middleware
84
+
85
+ ```typescript
86
+ app.post(
87
+ "/api/users",
88
+ route()
89
+ .use(requireAuth) // adds { userId: string }
90
+ .use(validateBody(userSchema)) // adds { body: UserType }
91
+ .handler((req, res) => {
92
+ // TypeScript knows about both userId and body!
93
+ res.json({ userId: req.userId, user: req.body });
94
+ })
95
+ );
96
+ ```
97
+
98
+ **See the [examples/](./examples) directory for more:**
99
+ - [Authentication](./examples/auth.ts) - Direct middleware and optional auth patterns
100
+ - [Zod Validation](./examples/zod-validation.ts) - Request body validation with type inference
101
+ - [Error Handling](./examples/error-handling.ts) - Throwing errors that flow to Express handlers
102
+
103
+ ### Error Handling
104
+
105
+ Middlewares can throw exceptions, and they'll automatically be caught and passed to Express error handlers:
106
+
107
+ ```typescript
108
+ const requireAuth = middleware<{ userId: string }>((req) => {
109
+ const token = req.headers.authorization?.substring(7);
110
+ if (!token) {
111
+ throw new Error("Unauthorized"); // Automatically caught!
112
+ }
113
+ return { userId: token };
114
+ });
115
+
116
+ // Express error handler will catch the error
117
+ app.use((err, req, res, next) => {
118
+ res.status(500).json({ error: err.message });
119
+ });
120
+ ```
121
+
122
+ This works seamlessly with async middleware too - rejected promises are automatically handled.
123
+
124
+ ## API
125
+
126
+ ### `route()`
127
+
128
+ Creates a new route builder for chaining middleware.
129
+
130
+ ```typescript
131
+ app.get(
132
+ "/path",
133
+ route()
134
+ .use(middleware1)
135
+ .use(middleware2)
136
+ .handler(finalHandler)
137
+ );
138
+ ```
139
+
140
+ ### `middleware<TAdd>(fn)`
141
+
142
+ Creates a typed middleware that adds properties to the request.
143
+
144
+ **Parameters:**
145
+ - `fn: (req: Request, res: Response) => TAdd | Promise<TAdd>` - Function that returns properties to add
146
+
147
+ **Returns:** `Middleware<TAdd>`
148
+
149
+ ```typescript
150
+ const myMiddleware = middleware<{ customProp: string }>((req, res) => {
151
+ return { customProp: "value" };
152
+ });
153
+ ```
154
+
155
+ ### `Middleware<TReq>`
156
+
157
+ Type for middleware functions that augment the request object.
158
+
159
+ ```typescript
160
+ type Middleware<TReq = {}> = (
161
+ req: Omit<Request, keyof TReq> & TReq,
162
+ res: Response,
163
+ next: NextFunction
164
+ ) => void | Promise<void>;
165
+ ```
166
+
167
+ ## License
168
+
169
+ MIT
170
+
171
+ ## Contributing
172
+
173
+ Found a bug or want to add a feature? Pull requests are welcome.
174
+
175
+ ## Author
176
+
177
+ Thomas Pregenzer
package/dist/index.cjs ADDED
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ middleware: () => middleware,
24
+ route: () => route
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+ var RouteBuilder = class {
28
+ constructor() {
29
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
30
+ this.middlewares = [];
31
+ }
32
+ /**
33
+ * Adds a middleware to the chain and merges its type into the request.
34
+ *
35
+ * @template TAdd - The type of properties this middleware adds to the request
36
+ * @param middleware - The middleware function to add
37
+ * @returns A new RouteBuilder with accumulated request types
38
+ */
39
+ use(middleware2) {
40
+ this.middlewares.push(middleware2);
41
+ return this;
42
+ }
43
+ /**
44
+ * Finalizes the route by adding the handler function.
45
+ * Returns an array of Express RequestHandlers ready to be used with app.get(), app.post(), etc.
46
+ *
47
+ * @param handler - The final route handler with access to all accumulated request properties
48
+ * @returns Array of RequestHandler functions to pass to Express route methods
49
+ *
50
+ * @example
51
+ * app.post('/api/users', route()
52
+ * .use(authMiddleware)
53
+ * .handler((req, res) => {
54
+ * // Handler implementation
55
+ * })
56
+ * );
57
+ */
58
+ handler(handler) {
59
+ return [...this.middlewares, handler];
60
+ }
61
+ };
62
+ var route = () => new RouteBuilder();
63
+ var middleware = (fn) => {
64
+ return async (req, res, next) => {
65
+ const result = await fn(req, res);
66
+ Object.assign(req, result);
67
+ next();
68
+ };
69
+ };
70
+ // Annotate the CommonJS export names for ESM import in node:
71
+ 0 && (module.exports = {
72
+ middleware,
73
+ route
74
+ });
@@ -0,0 +1,113 @@
1
+ import { Request, Response, NextFunction, RequestHandler } from 'express';
2
+
3
+ /**
4
+ * Type-safe middleware function that can augment the Express Request object.
5
+ *
6
+ * @template TReq - The type representing additional properties added to the request object
7
+ *
8
+ * @example
9
+ * // See examples/auth.ts for a complete authentication middleware example
10
+ * const requireAuth: Middleware<{ userId: string }> = middleware((req) => {
11
+ * const token = req.headers.authorization?.substring(7);
12
+ * if (!token) throw new Error('Unauthorized');
13
+ * return { userId: token };
14
+ * });
15
+ */
16
+ type Middleware<TReq = {}> = (req: Omit<Request, keyof TReq> & TReq, res: Response, next: NextFunction) => void | Promise<void>;
17
+ /**
18
+ * RouteBuilder provides an API for type-safe middleware chains.
19
+ *
20
+ * 1. Chain multiple middleware with `.use()`
21
+ * 2. Accumulate type information about request properties
22
+ * 3. Ensure the final handler has access to all augmented request properties
23
+ *
24
+ * @template TReq - Accumulated type of all request augmentations from chained middleware
25
+ *
26
+ * @example
27
+ * // See examples/auth.ts and examples/zod-validation.ts for complete examples
28
+ * const userSchema = z.object({ name: z.string(), email: z.string().email() });
29
+ *
30
+ * app.post('/api/users', route()
31
+ * .use(requireAuth) // adds { userId: string }
32
+ * .use(validateBody(userSchema)) // adds { body: { name: string, email: string } }
33
+ * .handler((req, res) => {
34
+ * // TypeScript knows req.userId and req.body exist with correct types
35
+ * res.json({ userId: req.userId, user: req.body });
36
+ * })
37
+ * );
38
+ */
39
+ declare class RouteBuilder<TReq = {}> {
40
+ private middlewares;
41
+ /**
42
+ * Adds a middleware to the chain and merges its type into the request.
43
+ *
44
+ * @template TAdd - The type of properties this middleware adds to the request
45
+ * @param middleware - The middleware function to add
46
+ * @returns A new RouteBuilder with accumulated request types
47
+ */
48
+ use<TAdd>(middleware: Middleware<TReq & TAdd>): RouteBuilder<TReq & TAdd>;
49
+ /**
50
+ * Finalizes the route by adding the handler function.
51
+ * Returns an array of Express RequestHandlers ready to be used with app.get(), app.post(), etc.
52
+ *
53
+ * @param handler - The final route handler with access to all accumulated request properties
54
+ * @returns Array of RequestHandler functions to pass to Express route methods
55
+ *
56
+ * @example
57
+ * app.post('/api/users', route()
58
+ * .use(authMiddleware)
59
+ * .handler((req, res) => {
60
+ * // Handler implementation
61
+ * })
62
+ * );
63
+ */
64
+ handler(handler: (req: Omit<Request, keyof TReq> & TReq, res: Response) => void | Promise<void>): RequestHandler[];
65
+ }
66
+ /**
67
+ * Creates a new RouteBuilder instance to start composing a type-safe middleware chain.
68
+ *
69
+ * @returns A new RouteBuilder with no middleware attached
70
+ *
71
+ * @example
72
+ * // See examples/auth.ts for complete middleware examples
73
+ * app.get('/api/profile', route()
74
+ * .use(requireAuth)
75
+ * .handler((req, res) => {
76
+ * res.json({ userId: req.userId });
77
+ * })
78
+ * );
79
+ */
80
+ declare const route: () => RouteBuilder<{}>;
81
+ /**
82
+ * Helper function to create a typed middleware that augments the request object.
83
+ *
84
+ * @template TAdd - The type of properties to add to the request
85
+ * @param fn - A function that returns the properties to add to the request
86
+ * @returns A Middleware function that merges the returned properties into req
87
+ *
88
+ * The middleware function:
89
+ * - Executes the provided function
90
+ * - Merges the returned object into the request using Object.assign
91
+ * - Calls next() to continue to the next middleware/handler
92
+ *
93
+ * @example
94
+ * // See examples/auth.ts and examples/zod-validation.ts for complete examples
95
+ * const requireAuth: Middleware<{ userId: string }> = middleware((req) => {
96
+ * const authHeader = req.headers.authorization;
97
+ * if (!authHeader || !authHeader.startsWith('Bearer ')) {
98
+ * throw new Error('Missing or invalid authorization header');
99
+ * }
100
+ * const token = authHeader.substring(7);
101
+ * return { userId: token };
102
+ * });
103
+ *
104
+ * // Use in routes
105
+ * route()
106
+ * .use(requireAuth)
107
+ * .handler((req, res) => {
108
+ * res.json({ userId: req.userId });
109
+ * });
110
+ */
111
+ declare const middleware: <TAdd>(fn: (req: Request, res: Response) => Promise<TAdd> | TAdd) => Middleware<TAdd>;
112
+
113
+ export { type Middleware, middleware, route };
@@ -0,0 +1,113 @@
1
+ import { Request, Response, NextFunction, RequestHandler } from 'express';
2
+
3
+ /**
4
+ * Type-safe middleware function that can augment the Express Request object.
5
+ *
6
+ * @template TReq - The type representing additional properties added to the request object
7
+ *
8
+ * @example
9
+ * // See examples/auth.ts for a complete authentication middleware example
10
+ * const requireAuth: Middleware<{ userId: string }> = middleware((req) => {
11
+ * const token = req.headers.authorization?.substring(7);
12
+ * if (!token) throw new Error('Unauthorized');
13
+ * return { userId: token };
14
+ * });
15
+ */
16
+ type Middleware<TReq = {}> = (req: Omit<Request, keyof TReq> & TReq, res: Response, next: NextFunction) => void | Promise<void>;
17
+ /**
18
+ * RouteBuilder provides an API for type-safe middleware chains.
19
+ *
20
+ * 1. Chain multiple middleware with `.use()`
21
+ * 2. Accumulate type information about request properties
22
+ * 3. Ensure the final handler has access to all augmented request properties
23
+ *
24
+ * @template TReq - Accumulated type of all request augmentations from chained middleware
25
+ *
26
+ * @example
27
+ * // See examples/auth.ts and examples/zod-validation.ts for complete examples
28
+ * const userSchema = z.object({ name: z.string(), email: z.string().email() });
29
+ *
30
+ * app.post('/api/users', route()
31
+ * .use(requireAuth) // adds { userId: string }
32
+ * .use(validateBody(userSchema)) // adds { body: { name: string, email: string } }
33
+ * .handler((req, res) => {
34
+ * // TypeScript knows req.userId and req.body exist with correct types
35
+ * res.json({ userId: req.userId, user: req.body });
36
+ * })
37
+ * );
38
+ */
39
+ declare class RouteBuilder<TReq = {}> {
40
+ private middlewares;
41
+ /**
42
+ * Adds a middleware to the chain and merges its type into the request.
43
+ *
44
+ * @template TAdd - The type of properties this middleware adds to the request
45
+ * @param middleware - The middleware function to add
46
+ * @returns A new RouteBuilder with accumulated request types
47
+ */
48
+ use<TAdd>(middleware: Middleware<TReq & TAdd>): RouteBuilder<TReq & TAdd>;
49
+ /**
50
+ * Finalizes the route by adding the handler function.
51
+ * Returns an array of Express RequestHandlers ready to be used with app.get(), app.post(), etc.
52
+ *
53
+ * @param handler - The final route handler with access to all accumulated request properties
54
+ * @returns Array of RequestHandler functions to pass to Express route methods
55
+ *
56
+ * @example
57
+ * app.post('/api/users', route()
58
+ * .use(authMiddleware)
59
+ * .handler((req, res) => {
60
+ * // Handler implementation
61
+ * })
62
+ * );
63
+ */
64
+ handler(handler: (req: Omit<Request, keyof TReq> & TReq, res: Response) => void | Promise<void>): RequestHandler[];
65
+ }
66
+ /**
67
+ * Creates a new RouteBuilder instance to start composing a type-safe middleware chain.
68
+ *
69
+ * @returns A new RouteBuilder with no middleware attached
70
+ *
71
+ * @example
72
+ * // See examples/auth.ts for complete middleware examples
73
+ * app.get('/api/profile', route()
74
+ * .use(requireAuth)
75
+ * .handler((req, res) => {
76
+ * res.json({ userId: req.userId });
77
+ * })
78
+ * );
79
+ */
80
+ declare const route: () => RouteBuilder<{}>;
81
+ /**
82
+ * Helper function to create a typed middleware that augments the request object.
83
+ *
84
+ * @template TAdd - The type of properties to add to the request
85
+ * @param fn - A function that returns the properties to add to the request
86
+ * @returns A Middleware function that merges the returned properties into req
87
+ *
88
+ * The middleware function:
89
+ * - Executes the provided function
90
+ * - Merges the returned object into the request using Object.assign
91
+ * - Calls next() to continue to the next middleware/handler
92
+ *
93
+ * @example
94
+ * // See examples/auth.ts and examples/zod-validation.ts for complete examples
95
+ * const requireAuth: Middleware<{ userId: string }> = middleware((req) => {
96
+ * const authHeader = req.headers.authorization;
97
+ * if (!authHeader || !authHeader.startsWith('Bearer ')) {
98
+ * throw new Error('Missing or invalid authorization header');
99
+ * }
100
+ * const token = authHeader.substring(7);
101
+ * return { userId: token };
102
+ * });
103
+ *
104
+ * // Use in routes
105
+ * route()
106
+ * .use(requireAuth)
107
+ * .handler((req, res) => {
108
+ * res.json({ userId: req.userId });
109
+ * });
110
+ */
111
+ declare const middleware: <TAdd>(fn: (req: Request, res: Response) => Promise<TAdd> | TAdd) => Middleware<TAdd>;
112
+
113
+ export { type Middleware, middleware, route };
package/dist/index.js ADDED
@@ -0,0 +1,48 @@
1
+ // src/index.ts
2
+ var RouteBuilder = class {
3
+ constructor() {
4
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
5
+ this.middlewares = [];
6
+ }
7
+ /**
8
+ * Adds a middleware to the chain and merges its type into the request.
9
+ *
10
+ * @template TAdd - The type of properties this middleware adds to the request
11
+ * @param middleware - The middleware function to add
12
+ * @returns A new RouteBuilder with accumulated request types
13
+ */
14
+ use(middleware2) {
15
+ this.middlewares.push(middleware2);
16
+ return this;
17
+ }
18
+ /**
19
+ * Finalizes the route by adding the handler function.
20
+ * Returns an array of Express RequestHandlers ready to be used with app.get(), app.post(), etc.
21
+ *
22
+ * @param handler - The final route handler with access to all accumulated request properties
23
+ * @returns Array of RequestHandler functions to pass to Express route methods
24
+ *
25
+ * @example
26
+ * app.post('/api/users', route()
27
+ * .use(authMiddleware)
28
+ * .handler((req, res) => {
29
+ * // Handler implementation
30
+ * })
31
+ * );
32
+ */
33
+ handler(handler) {
34
+ return [...this.middlewares, handler];
35
+ }
36
+ };
37
+ var route = () => new RouteBuilder();
38
+ var middleware = (fn) => {
39
+ return async (req, res, next) => {
40
+ const result = await fn(req, res);
41
+ Object.assign(req, result);
42
+ next();
43
+ };
44
+ };
45
+ export {
46
+ middleware,
47
+ route
48
+ };
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "express-typed-routes",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Type-safe middleware composition for Express",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "scripts": {
20
+ "build": "tsup src/index.ts --format cjs,esm --dts --clean",
21
+ "test": "vitest run",
22
+ "test:watch": "vitest",
23
+ "lint": "eslint src",
24
+ "lint:fix": "eslint src --fix",
25
+ "prepublishOnly": "npm run build"
26
+ },
27
+ "keywords": [
28
+ "express",
29
+ "typescript",
30
+ "middleware",
31
+ "type-safe"
32
+ ],
33
+ "author": "Thomas Pregenzer",
34
+ "license": "MIT",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "https://github.com/PregOfficial/express-typed-routes"
38
+ },
39
+ "peerDependencies": {
40
+ "express": "^5.0.0"
41
+ },
42
+ "devDependencies": {
43
+ "@types/express": "^5.0.6",
44
+ "@types/node": "^24.10.1",
45
+ "@typescript-eslint/eslint-plugin": "^8.48.1",
46
+ "@typescript-eslint/parser": "^8.48.1",
47
+ "eslint": "^9.39.1",
48
+ "express": "^5.2.1",
49
+ "tsup": "^8.5.1",
50
+ "typescript": "^5.9.3",
51
+ "typescript-eslint": "^8.48.1",
52
+ "vitest": "^4.0.15"
53
+ }
54
+ }