Next.js Discord

Discord Forum

NEXT_REDIRECT on middleware

Answered
Dovekie posted this in #help-forum
Open in Discord
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 Giant panda
redirect is not meant to be called in the middleware. Use NextResponse.redirect instead.
View full answer

6 Replies

Giant panda
redirect is not meant to be called in the middleware. Use NextResponse.redirect instead.
Answer
Giant panda
The docs have examples and notes on that specifically
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 ?
Giant panda
That page doesn't mention the middleware for one. Also you should read the actual middleware docs.
DovekieOP
Copy that, will do
Thanks for the help!