A lightweight middleware enhancer for Next.js, allowing route-based middleware execution with support for sequential middleware execution.
- Route Matching: Supports Next.js
matcher
patterns to apply middleware based on specific routes. - Multiple Middleware Execution: Allows executing multiple middleware functions sequentially.
- Automatic Response Handling: Returns
NextResponse.next()
if no matching middleware is found.
Install the package using npm or pnpm:
npm install next-middleware-enhancer
or
pnpm add next-middleware-enhancer
Define your middleware in middleware.ts
and use createMiddleware
to apply route-based handlers.
import { NextRequest, NextResponse } from "next/server";
import { createMiddleware } from "next-middleware-enhancer";
const authMiddleware = (req: NextRequest) => {
if (!req.headers.get("Authorization")) {
return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
}
};
const { middleware, config } = createMiddleware([{ matcher: "/admin", handler: authMiddleware }]);
export { middleware, config };
🛠 Usage (Multiple Handlers) Apply multiple middleware functions sequentially for a route:
import { NextRequest, NextResponse } from "next/server";
import { createMiddleware } from "next-middleware-enhancer";
const logMiddleware = (req: NextRequest) => console.log(`Request: ${req.nextUrl.pathname}`);
const authMiddleware = (req: NextRequest) => {
if (!req.headers.get("Authorization")) return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
};
const adminMiddleware = (req: NextRequest) => {
if (req.headers.get("Authorization") !== "admin-secret")
return NextResponse.json({ message: "Forbidden" }, { status: 403 });
};
const { middleware, config } = createMiddleware([
{ matcher: "/admin", handler: [logMiddleware, authMiddleware, adminMiddleware] },
]);
export { middleware, config };
Execution Flow: 1️⃣ Logs request path → 2️⃣ Checks auth → 3️⃣ Verifies admin access 🚀
Creates a Next.js middleware function that applies the specified middleware handlers based on route patterns.
type MiddlewareFunction = (req: NextRequest) => NextResponse | void | Promise<NextResponse | void>;
type MiddlewareConfig = { matcher: string; handler: MiddlewareFunction | MiddlewareFunction[] };
type MiddlewareList = MiddlewareConfig[];
{
middleware: (req: NextRequest) => NextResponse | void;
config: { matcher: string[] };
}
- Requests are matched against
matcher
patterns. - Matched middleware functions execute sequentially.
- A
NextResponse
returned from a middleware stops execution. - If no middleware handles the request,
NextResponse.next()
is returned.
This project is licensed under the MIT License.
Feel free to contribute to this project by opening issues or pull requests!