Next.js Discord

Discord Forum

NEXT_REDIRECT on middleware

Answered
Dovekie posted this in #help-forum
Open in Discord
Avatar
DovekieOP
Hello everyone, I have the following code:


export function middleware(request: NextRequest) {
    console.log('middleware run')
    const cookies = request.cookies.getAll()
    if(!cookies.length){
        redirect("/auth/login")
    }
    // return NextResponse.next()
}


As it says in the title, I'm getting a "NEXT_REDIRECT" error on my middleware when the user is not authenticated.

I would expect to get redirected to the URL I specificied instead.

Any ideas why this is happening ?
Answered by Asian black bear
redirect is not meant to be called in the middleware. Use NextResponse.redirect instead.
View full answer

6 Replies

Avatar
Asian black bear
redirect is not meant to be called in the middleware. Use NextResponse.redirect instead.
Answer
Avatar
Asian black bear
The docs have examples and notes on that specifically
Avatar
DovekieOP
I see, I was looking at the docs for hours and I didn't see it getting mentioned https://nextjs.org/docs/app/api-reference/functions/redirect

Is there a chance you remember where it is off top of your head ?
Avatar
Asian black bear
That page doesn't mention the middleware for one. Also you should read the actual middleware docs.
Avatar
DovekieOP
Copy that, will do
Thanks for the help!