'How to unprotect route in next js middleware
so I want to unprotect the login page and here is my folder structure:
here is my middleware:
import { NextResponse, NextRequest } from "next/server";
export async function middleware(req, ev) {
if (req.pathname === "login") {
return NextResponse.next();
}
const token = req.cookies.token;
if (!token) {
return NextResponse.redirect("/login");
}
return NextResponse.next();
}
so how do I make it so the middleware does not apply to login.js.
Edit: it now returns [webpack.cache.PackFileCacheStrategy] Caching failed for pack: Error: Unable to snapshot resolve dependencies
code for this project is here
Solution 1:[1]
so I solved the error I was not getting the pathname from req.nextUrl and here is the correct code:
import { NextResponse, NextRequest } from "next/server";
export async function middleware(req, ev) {
const { pathname } = req.nextUrl;
const token = req.cookies.token;
if (pathname == "/login" && !token) {
return NextResponse.next();
}
if (!token) {
return NextResponse.redirect("/login");
}
return NextResponse.next();
}
Solution 2:[2]
You can check if the request is for the /login page itself, and bail early.
Checkout all properties on NextRequest that are available.
import { NextResponse, NextRequest } from "next/server";
export async function middleware(req, ev) {
if( req.pathname === 'login'){
return NextResponse.next();
}
const token = req.cookies.token;
if (!token) {
return NextResponse.redirect("/login");
}
return NextResponse.next();
}
Solution 3:[3]
The Accepted answer helped me a lot. I'm adding my solution because I had to make some modifications.
I used [...nextauth].js file with jwt and session callbacks and when I used the solution from accepted answer, I was getting ERR_TOO_MANY_REQUESTS cycle. My solution was to add a few more URLs:
import { NextResponse } from "next/server";
import { getToken } from 'next-auth/jwt';
export default async function middleware(req, ev) {
const { pathname } = req.nextUrl;
const token = await getToken({ req, secret: process.env.JWT_SECRET });
if ((pathname == "/api/auth/signin" || pathname == "/favicon.ico" || pathname == "/api/auth/callback/credentials") && !token) {
return NextResponse.next();
}
if (!token) {
return NextResponse.rewrite(new URL('/api/auth/signin', req.url));
}
return NextResponse.next();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shahab Athar |
| Solution 2 | Ivan V. |
| Solution 3 | Son Goku ssj4 |

