Next.JS middleware redirects, but doesn't change the browser's URL

42 Views Asked by At

Question: After I log in successfully and the token gets created, I get redirected to the "/" route, which is correct. However, when I click on the "/dashboard" link (which I added as a Link to my homepage so I could access it more easily), then the dashboard page gets rendered correctly, YET the browser's URL displays "/login"! But why? I just can't seem to find the solution and answer to this problem. AFTER I refresh the page once (manually in the browser), the error is fixed.

All my pages are client components.

Middleware Code:

import { NextResponse } from "next/server";

export const middleware = (request) => {
  const path = request.nextUrl.pathname;
  console.log(path)

  const isPublicPath = path === "/login" || path === "/register" || path === "/"

  const token = request.cookies.get("token")?.value || "";

  if (isPublicPath && token && path !== "/") {
    console.log("PUBLIC PATH ACCESSED")
    return NextResponse.redirect(new URL("/", request.nextUrl));
  }

  if (!isPublicPath && !token) {
    console.log("NON-PUBLIC PATH ACCESSED")
    return NextResponse.redirect(new URL("/login", request.nextUrl));
  }
};

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

There are 0 best solutions below