Next.js Discord

Discord Forum

Why is my middleware causing infinite redirect anyway?

Unanswered
Dogue Brasileiro posted this in #help-forum
Open in Discord
Dogue BrasileiroOP
export default async function middleware(req: NextRequest) {
    const url = req.nextUrl;

    // Get hostname of request (e.g. demo.vercel.pub, demo.localhost:3000)
    const hostname = req.headers
        .get("host")!
        .replace(".localhost:3000", `.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}`);

    const searchParams = req.nextUrl.searchParams.toString();
    // Get the pathname of the request (e.g. /, /about, /blog/first-post)
    const path = `${url.pathname}${searchParams.length > 0 ? `?${searchParams}` : ""
        }`;


    if (hostname == `app.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}`) {
        const publicRoutes = [
            "/login", "/signup", "/sso/google"
        ]
        let session = false
        let access_token = req.cookies.get("access_token")?.value
        let refresh_token = req.cookies.get("refresh_token")?.value

const loginRedirect = NextResponse.redirect(new URL("/login", req.url));

   if (refresh_token && !access_token) {
loginRedirect.cookies.set("refresh_token", "", { maxAge: 0, sameSite: 'lax', domain: `.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}` });
return loginRedirect
   }
}

The problem is it keeps redirecting to the login page, and run middleware again and redirect again.

1 Reply

Dogue BrasileiroOP
can someone tell me why its keep redirecting to the same page again and again?