skip to Main Content

I am trying to redirect a user to /login if the authentication token from Laravel is not valid. So I am trying to fetch the user and if resp.ok() is false then I delete the invalid "token" cookie and redirect the user to /login. But I keep on getting errors in my browser.

It is about the third if-statement in the code sample down below.

Error: The page isn’t redirecting properly Firefox has detected that
the server is redirecting the request for this address in a way that
will never complete. This problem can sometimes be caused by disabling
or refusing to accept cookies.

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export async function middleware(req: NextRequest) {
  // Add protected routes here
  const url = req.nextUrl.clone();

  if (req.nextUrl.pathname === "/login" && req.cookies.has("token")) {
    url.pathname = "/";
    return NextResponse.redirect(url);
  }

  if (
    !req.cookies.has("token") &&
    req.nextUrl.pathname !== "/login" &&
    !req.nextUrl.pathname.startsWith("/_next")
  ) {
    url.pathname = "/login";
    return NextResponse.redirect(url);
  }
  
  if (req.cookies.has("token")) {
    const user = await fetch(`http://10.129.23.206:8080/api/user`, {
      headers: {
        "Authorization": `Bearer ${req.cookies.get("token")}`,
      }
    })
    
    console.log(user)

    if (!user.ok){
      req.cookies.delete("token")
      url.pathname = "/login";
      return NextResponse.redirect(url)
    }
  }
}

export const config = {
  matcher: ["/", "/create", "/search", "/:slug*", "/login"],
};

2

Answers


  1. I think fetching user is failing and then in this if block

    if (!user.ok){
          req.cookies.delete("token")
          url.pathname = "/login";
          return NextResponse.redirect(url)
        }
    

    you are deleting the token, after that when you make another request wihtout token, so this if gets executed and you are redirected to "login" again:

    if (
        !req.cookies.has("token") &&
        req.nextUrl.pathname !== "/login" &&
        !req.nextUrl.pathname.startsWith("/_next")
      ) {
        url.pathname = "/login";
        return NextResponse.redirect(url);
      }
    

    fetching user code should be try/catch block, and in catch block you should handle the error accordingly. maybe you send the message to the browser, browser will display the error on form instead of redirecting again.

    Login or Signup to reply.
  2. This is how I implemented it in my NextJS middleware.

    export async function middleware(request: NextRequest){
        (...)
        await fetch("http://localhost:3000/api/foo", {method: "POST", body: JSON.stringify(data)});
        (...)
    }
    

    As NextJS middleware (the Edge Runtime) does not support Node.js APIs and globals, it should be a better way to continue some NodeJS operations in API router.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search