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
CodePudding user response:
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();
}
CodePudding user response:
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();
}