Search code examples
authenticationnext.jsjwtnext.js13app-router

Localhost redirected you too many times NextJs 13 and JWT verify middleware


Everything works perfectly fine one problem is that when I am logged In I am redirected to "/" page and if a user wanna go to "/login" or "/register" page even after being logged In they should be redirected to "/" page how can I add that feature in this code right now I am able get to "/login" page even after logged in but the page says localhost redirected you too many times error in the web page.

The code middleware.js :

import { NextResponse } from "next/server";
import { verify } from "jsonwebtoken";

export function middleware(request) {
  const secret = process.env.JWT_SECRET;
  const jwt = request.cookies.get("jwt")?.value;
  const path = request.nextUrl.pathname;

  if (!jwt && !["/login", "/register"].includes(path)) {
    return NextResponse.redirect(new URL("/login", request.url));
  } else if (jwt && (path === "/login" || path === "/register")) {
    try {
      verify(jwt, secret);
      return NextResponse.redirect(new URL("/", request.url));
    } catch (error) {
      return NextResponse.redirect(new URL("/login", request.url));
    }
  }
  return NextResponse.next();
}

export const config = {
  matcher: ["/dashboard/:path*", "/login", "/register", "/"],
};

I was trying successful login and register using JWT verify and NextJs


Solution

  • I think verify(jwt, secret) is failing. it is throwing error. so you are running into catch block. In the catch block you are redirected to the "login` again. So, you are hitting

    else if (jwt && (path === "/login" || path === "/register"))
    

    because jwt is valid and path==="/login". since verify is throwing error, you are hitting the catch block so you are kinda in a loop