reactjstypescriptnext.jsmiddlewarenext-auth

NextJS Middleware causing "localhost redirected you too many times" error


I just implemented email/password authentication into my locally hosted NextJS app with NextAuth. When I created the middleware to protect routes, whenever I clicked the sign out button, I got the error "localhost redirected you too many times." Image of the error

This is my middleware.ts file:

import { NextRequest, NextResponse } from 'next/server'

export default async function middleware(req: NextRequest) {
    const path = req.nextUrl.pathname;

    const session = await getToken({
        req,
        secret: process.env.NEXTAUTH_SECRET,
    });
    if (!session) {
        return NextResponse.redirect(new URL('/login', req.url))
    } else if (session && (path === '/login' || path === '/signup')) {
        return NextResponse.redirect(new URL('/', req.url))
    }
    return NextResponse.next()
}

Is there a way to protect all routes like this without middleware or make function without redirects? TYA


Solution

  • It occurs because you wrote an if with only a condition (!session), then always redirected to the same route (/login) causing too many redirects to the same route.

    To solve the problem change the if to !session && path !== "/login"