Middleware redirect does not block authenticated users from /auth/* routes in App Router #88724
-
SummaryI’m using Next.js App Router with Edge middleware and JWT-based auth. Middleware does run and logs are printed, but the redirect is ignored What I expect If a valid auth cookie exists:
What actually happens
Additional informationCode (middleware)
`ts
export function middleware(req: NextRequest) {
const token = req.cookies.get("token")?.value;
const { pathname } = req.nextUrl;
if (pathname.startsWith("/auth") && token) {
const { role } = verifyToken(token);
return NextResponse.redirect(
new URL(
role === "ADMIN"
? "/admin/dashboard"
: "/student/dashboard",
req.url
)
);
}
return NextResponse.next();
}
export const config = {
matcher: ["/auth/:path*"],
};Example |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
its because jsowebtoken library doesn't work in Edge Runtime. Replace jsonwebtoken with a library like jose (Edge-compatible JWT library). Next.js middleware runs on Edge by default, but jsonwebtoken and it uses Node.js crypto APIs that aren't available there. |
Beta Was this translation helpful? Give feedback.
its because jsowebtoken library doesn't work in Edge Runtime. Replace jsonwebtoken with a library like jose (Edge-compatible JWT library).
Next.js middleware runs on Edge by default, but jsonwebtoken and it uses Node.js crypto APIs that aren't available there.