Next.js Discord

Discord Forum

How to handle cookies on middleware??

Answered
Juniper Titmouse posted this in #help-forum
Open in Discord
Avatar
Juniper TitmouseOP
Hello, I would like to know how I can manage cookies inside middleware.
I have seen the doc but it doesn't explain how to..

here is the actual case.

if (languageCookie){
        if (i18n.locales.includes(languageCookie as Locale)){
          return NextResponse.redirect(new URL(`/${languageCookie}`, request.url))
        }else{
          //How to delete cookie ??
        }
    }


Here is an other case where i tried to do the following

const preferedLanguage = getPreferredLanguage(languageHeader)
      return NextResponse.redirect(new URL(`/${preferedLanguage}`, request.url)).cookies.set(LANGUAGE_COOKIE, preferedLanguage, languageCookieOptions)


This rised the following error :
Expected an instance of Response to be returned

TL;DR : I need a way to add or remove some cookies from the middleware function.
Answered by Plague
it would be like this:
 
const response = NextResponse.redirect(new URL(`your url`, request.url))

response.cookies.set/delete()

return response
View full answer

12 Replies

Avatar
App router or pages router?
Avatar
Juniper TitmouseOP
App router
Avatar
You can just call [cookies](https://nextjs.org/docs/app/api-reference/functions/cookies) from next/headers and work with cookies like in any other server environment within app router.
Avatar
Juniper TitmouseOP
So I should for example work like this ?
const cookieStore = cookies()
cookieStore.set(LANGUAGE_COOKIE, preferedLanguage, languageCookieOptions)
return NextResponse.redirect(new URL(`/${preferedLanguage}`, request.url))

??
And same for delete then.
Avatar
My mistake, you want to set/delete cookies not read them.

Type the request object like so (request: NextRequest) then you can call request.cookies.set/delete()
Avatar
Juniper TitmouseOP
I tried, and you cannot delete or set on the request because it's not the response
I mean, you can but it won't do anything
Avatar
const response = NextResponse.next() then response.cookies.set/delete()
then return that response
Avatar
Juniper TitmouseOP
I saw this example on internet, but can you do the following ?
const response = NextResponse.next() then response.cookies.set/delete()
return response.redirect() 
?
Avatar
it would be like this:
 
const response = NextResponse.redirect(new URL(`your url`, request.url))

response.cookies.set/delete()

return response
Answer
Avatar
Juniper TitmouseOP
Ok gotcha but a bit verbose sadly but thanks it should indeed work