nextjs-middleware-stack 1.0.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,65 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
37
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
38
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
39
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
40
+
41
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
42
+
43
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
44
+
45
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
46
+
47
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
48
+
49
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
50
+
51
+ END OF TERMS AND CONDITIONS
52
+
53
+ Copyright 2025 Islam Yamor
54
+
55
+ Licensed under the Apache License, Version 2.0 (the "License");
56
+ you may not use this file except in compliance with the License.
57
+ You may obtain a copy of the License at
58
+
59
+ http://www.apache.org/licenses/LICENSE-2.0
60
+
61
+ Unless required by applicable law or agreed to in writing, software
62
+ distributed under the License is distributed on an "AS IS" BASIS,
63
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
64
+ See the License for the specific language governing permissions and
65
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,153 @@
1
+ # 🚣️ `middlewareStack` – A Lightweight Middleware Router for Next.js
2
+
3
+ A composable middleware stack for Next.js, supporting both `string`-based route patterns (with dynamic parameters and wildcards) and raw `RegExp` objects.
4
+
5
+ Perfect for building layered request logic like authentication, logging, redirects, or feature flags in Next.js Edge or Node middlewares.
6
+
7
+ ---
8
+
9
+ ## ✨ Features
10
+
11
+ - ✅ Simple pattern matching with support for:
12
+ - `:param` dynamic segments
13
+ - `**` wildcards (greedy)
14
+ - ✅ `RegExp` support
15
+ - ✅ Middleware short-circuiting (first matching response stops the stack)
16
+ - ✅ Fully compatible with `next/server` and middleware in `apps/<name>/src/middleware.ts`
17
+
18
+ ---
19
+
20
+ ## 📦 Installation
21
+
22
+ ```bash
23
+ npm install compare-path
24
+ ```
25
+
26
+ ---
27
+
28
+ ## 🧠 API
29
+
30
+ ### `middlewareStack(routes: [string | RegExp, MiddlewareHandler][])`
31
+
32
+ Creates a Next.js-compatible middleware handler from an ordered list of route matchers and handler functions.
33
+
34
+ #### Parameters:
35
+
36
+ - `routes`: An array of tuples where:
37
+ - The first item is a string pattern (e.g., `/users/:id`) or a RegExp.
38
+ - The second item is a handler function `(req: NextRequest) => Response | void | Promise<Response | void>`.
39
+
40
+ #### Returns:
41
+
42
+ - A function `(req: NextRequest) => Promise<Response | void>` – ready to be exported as default from `middleware.ts`.
43
+
44
+ ---
45
+
46
+ ## 📊 Supported Path Shapes
47
+
48
+ You can use either `string`-based shape patterns (powered by `compare-path`) or `RegExp`.
49
+
50
+ | Shape | Matches Path Example |
51
+ | --------------- | --------------------------- |
52
+ | `/user/:id` | `/user/42` |
53
+ | `/users/[id]` | `/users/42` (same as above) |
54
+ | `/docs/**/edit` | `/docs/api/v1/intro/edit` |
55
+ | `/a/:x/**/b/:y` | `/a/1/foo/bar/b/2` |
56
+
57
+ > Use RegExp when you need full regex control.
58
+
59
+ ---
60
+
61
+ ## 🧪 Example Usage (Auth Middleware)
62
+
63
+ ```ts
64
+ // File: apps/example-app/src/middleware.ts
65
+ import { NextResponse } from 'next/server'
66
+ import { middlewareStack } from './utils/middleware-stack'
67
+ import { validateAuthToken } from './utils/validate-jwt'
68
+
69
+ export default middlewareStack([
70
+ [
71
+ /^\/dashboard\/.*/,
72
+ async (req) => {
73
+ const token = req.cookies.get('AUTH_TOKEN')?.value
74
+ const isValid = token && (await validateAuthToken(token))
75
+ if (!isValid) return NextResponse.redirect(new URL('/login', req.url))
76
+ },
77
+ ],
78
+ [
79
+ '/public/:page',
80
+ async (req) => {
81
+ console.log('Logging public page hit')
82
+ },
83
+ ],
84
+ ])
85
+ ```
86
+
87
+ ---
88
+
89
+ ## 🧪 Example with String Matching
90
+
91
+ ```ts
92
+ // File: apps/example-app/src/middleware.ts
93
+ import { middlewareStack } from './utils/middleware-stack'
94
+
95
+ export default middlewareStack([
96
+ [
97
+ '/users/:id',
98
+ async (req) => {
99
+ // Handle specific user route
100
+ },
101
+ ],
102
+ [
103
+ 'cars/:id',
104
+ async (req) => {
105
+ // Same as above with different route
106
+ },
107
+ ],
108
+ [
109
+ 'hello/**',
110
+ async (req) => {
111
+ // Match anything starting with /hello/
112
+ },
113
+ ],
114
+ ])
115
+ ```
116
+
117
+ ---
118
+
119
+ ## 🧹 Integration in Next.js
120
+
121
+ You must also export the `config` to ensure the middleware applies to your desired routes:
122
+
123
+ ```ts
124
+ export const config = {
125
+ matcher: [
126
+ '/((?!_next|.*\\..*).*)', // Skip static assets
127
+ '/(api|trpc)(.*)', // Always include API routes
128
+ ],
129
+ runtime: 'nodejs',
130
+ }
131
+ ```
132
+
133
+ ---
134
+
135
+ ## 🧠 How It Works
136
+
137
+ Internally, `middlewareStack` will iterate through your routes and:
138
+
139
+ 1. Compare the current path to each route (using `compare-path` or RegExp).
140
+ 2. If matched, execute the handler.
141
+ 3. If a `Response` is returned from the handler, it stops further execution and returns immediately.
142
+
143
+ ---
144
+
145
+ ## 💡 Tips
146
+
147
+ - Middleware order matters! First match wins.
148
+ - Use RegExp for more complex or legacy patterns.
149
+ - Use string shapes for clean, readable routes with parameters.
150
+
151
+ ---
152
+
153
+ Islam Yamor.
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @file Automatically generated by barrelsby.
3
+ */
4
+ export * from "./main";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,QAAQ,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ /**
3
+ * @file Automatically generated by barrelsby.
4
+ */
5
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = { enumerable: true, get: function() { return m[k]; } };
10
+ }
11
+ Object.defineProperty(o, k2, desc);
12
+ }) : (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ o[k2] = m[k];
15
+ }));
16
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
17
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
18
+ };
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ __exportStar(require("./main"), exports);
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;GAEG;;;;;;;;;;;;;;;;AAEH,yCAAuB"}
package/dist/main.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ export type MiddlewareHandler = (req: NextRequest) => NextResponse | Response | void | Promise<NextResponse | Response | void>;
3
+ export declare function middlewareStack(routes: [string | RegExp, MiddlewareHandler][]): (req: NextRequest) => Promise<Response | undefined>;
4
+ //# sourceMappingURL=main.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAEvD,MAAM,MAAM,iBAAiB,GAAG,CAC9B,GAAG,EAAE,WAAW,KACb,YAAY,GAAG,QAAQ,GAAG,IAAI,GAAG,OAAO,CAAC,YAAY,GAAG,QAAQ,GAAG,IAAI,CAAC,CAAA;AAE7E,wBAAgB,eAAe,CAAC,MAAM,EAAE,CAAC,MAAM,GAAG,MAAM,EAAE,iBAAiB,CAAC,EAAE,IAC9D,KAAK,WAAW,mCAiB/B"}
package/dist/main.js ADDED
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.middlewareStack = middlewareStack;
13
+ const compare_path_1 = require("compare-path");
14
+ function middlewareStack(routes) {
15
+ return (req) => __awaiter(this, void 0, void 0, function* () {
16
+ const url = req.nextUrl.pathname;
17
+ for (const [pattern, handler] of routes) {
18
+ const isMatch = typeof pattern === 'string'
19
+ ? (0, compare_path_1.comparePath)(pattern, url)
20
+ : pattern instanceof RegExp
21
+ ? pattern.test(url)
22
+ : false;
23
+ if (isMatch) {
24
+ const result = yield handler(req);
25
+ if (result)
26
+ return result; // short-circuit if a handler returns a response
27
+ }
28
+ }
29
+ });
30
+ }
31
+ //# sourceMappingURL=main.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":";;;;;;;;;;;AAOA,0CAkBC;AAzBD,+CAA0C;AAO1C,SAAgB,eAAe,CAAC,MAA8C;IAC5E,OAAO,CAAO,GAAgB,EAAE,EAAE;QAChC,MAAM,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAA;QAEhC,KAAK,MAAM,CAAC,OAAO,EAAE,OAAO,CAAC,IAAI,MAAM,EAAE,CAAC;YACxC,MAAM,OAAO,GACX,OAAO,OAAO,KAAK,QAAQ;gBACzB,CAAC,CAAC,IAAA,0BAAW,EAAC,OAAO,EAAE,GAAG,CAAC;gBAC3B,CAAC,CAAC,OAAO,YAAY,MAAM;oBAC3B,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC;oBACnB,CAAC,CAAC,KAAK,CAAA;YAEX,IAAI,OAAO,EAAE,CAAC;gBACZ,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,CAAA;gBACjC,IAAI,MAAM;oBAAE,OAAO,MAAM,CAAA,CAAC,gDAAgD;YAC5E,CAAC;QACH,CAAC;IACH,CAAC,CAAA,CAAA;AACH,CAAC"}
package/package.json ADDED
@@ -0,0 +1,77 @@
1
+ {
2
+ "name": "nextjs-middleware-stack",
3
+ "version": "1.0.0",
4
+ "description": "Composable route-based middleware for Next.js Middleware.",
5
+ "author": "Islam Yamor",
6
+ "license": "Apache-2.0",
7
+ "main": "dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "prettier": "@samislam/prettier-config/next",
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "keywords": [
14
+ "nextjs",
15
+ "next",
16
+ "next.js",
17
+ "middleware",
18
+ "nextjs-middleware",
19
+ "next-middleware",
20
+ "next-middleware-stack",
21
+ "nextjs-stack",
22
+ "edge",
23
+ "nextjs-edge"
24
+ ],
25
+ "devDependencies": {
26
+ "@clscripts/barrelsby": "^2.8.1",
27
+ "@clscripts/chokidar-cli": "^4.0.3",
28
+ "@clscripts/cl-common": "^1.0.4",
29
+ "@clscripts/concurrently": "^9.2.0",
30
+ "@clscripts/cross-env": "^7.0.3",
31
+ "@clscripts/del-cli": "^6.0.0",
32
+ "@clscripts/echo-cli": "^2.0.0",
33
+ "@clscripts/eslint": "^9.30.1",
34
+ "@clscripts/nodemon": "^3.1.10",
35
+ "@clscripts/prettier": "^3.6.2",
36
+ "@clscripts/ts-node": "^10.9.2",
37
+ "@clscripts/ts-node-dev": "^2.0.0",
38
+ "@clscripts/ts-patch": "^3.3.0",
39
+ "@eslint/js": "^9.30.1",
40
+ "@samislam/prettier-config": "^1.1.7",
41
+ "@types/jest": "^30.0.0",
42
+ "@types/node": "^22.16.0",
43
+ "barrelsby": "^2.8.1",
44
+ "chalk": "4",
45
+ "chokidar-cli": "^3.0.0",
46
+ "cl-common": "^6.1.2",
47
+ "concurrently": "^9.2.0",
48
+ "cross-env": "^7.0.3",
49
+ "del-cli": "^6.0.0",
50
+ "echo-cli": "^2.0.0",
51
+ "eslint": "^9.30.1",
52
+ "jest": "^30.0.4",
53
+ "nodemon": "^3.1.10",
54
+ "prettier": "3.0.3",
55
+ "prettier-plugin-jsdoc": "^1.3.3",
56
+ "prettier-plugin-tailwindcss": "^0.6.13",
57
+ "ts-jest": "^29.4.0",
58
+ "ts-node": "^10.9.2",
59
+ "ts-node-dev": "^2.0.0",
60
+ "ts-patch": "^3.3.0",
61
+ "tsx": "^4.20.3",
62
+ "typescript-eslint": "^8.36.0",
63
+ "typescript-transform-paths": "^3.5.5"
64
+ },
65
+ "dependencies": {
66
+ "compare-path": "^1.2.0",
67
+ "next": "^15.3.5"
68
+ },
69
+ "scripts": {
70
+ "test": "jest",
71
+ "dev": "tsx ./scripts/dev.ts",
72
+ "lint": "tsx ./scripts/lint.ts",
73
+ "clean": "tsx ./scripts/clean.ts",
74
+ "build": "tsx ./scripts/build.ts",
75
+ "format": "tsx ./scripts/format.ts"
76
+ }
77
+ }