Search code examples
javascriptnode.jsreactjsnext.jsmiddleware

How to unprotect route in next js middleware


so I want to unprotect the login page and here is my folder structure:

enter image description here

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

  • 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();
    }