I'm working on a Next.js project and trying to implement multiple middleware in my application. While I've found examples of using a single middleware in Next.js using the next-connect
package, I prefer to achieve this without relying on any external packages.
I have a middleware.ts
file where I would like to define and use multiple middlewares. Here's the code snippet from my middleware.ts
file:
import { NextResponse, NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const userId = request.cookies.get('userId')
if (!userId) {
return NextResponse.redirect(new URL('/auth/login', request.nextUrl.origin).href);
}
return NextResponse.next();
}
export const config = {
matcher:'/profile/:path*',
};
Her's what i tried:
import { NextResponse, NextRequest } from "next/server";
export function profileMiddleware(request: NextRequest) {
const userId = request.cookies.get("userId");
if (!userId) {
return NextResponse.redirect(
new URL("/auth/login", request.nextUrl.origin).href
);
}
return NextResponse.next();
}
export function authMiddleware(request: NextRequest) {
const userId = request.cookies.get("userId");
if (userId) {
return NextResponse.redirect(
new URL("/", request.nextUrl.origin).href
);
}
return NextResponse.next();
}
export default {
middleware: [
{
matcher: '/profile/:path*',
handler: profileMiddleware,
},
{
matcher: '/auth/:path*',
handler: authMiddleware,
},
],
};