How to handle cookies on middleware??
Answered
Juniper Titmouse posted this in #help-forum
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.
Here is an other case where i tried to do the following
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.
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
12 Replies
App router or pages router?
Juniper TitmouseOP
App router
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.Juniper TitmouseOP
So I should for example work like this ?
??
And same for delete then.
const cookieStore = cookies()
cookieStore.set(LANGUAGE_COOKIE, preferedLanguage, languageCookieOptions)
return NextResponse.redirect(new URL(`/${preferedLanguage}`, request.url))
??
And same for delete then.
My mistake, you want to set/delete cookies not read them.
Type the request object like so
Type the request object like so
(request: NextRequest)
then you can call request.cookies.set/delete()
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
const response = NextResponse.next()
then response.cookies.set/delete()
then return that response
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()
?it would be like this:
const response = NextResponse.redirect(new URL(`your url`, request.url))
response.cookies.set/delete()
return response
Answer
Juniper TitmouseOP
Ok gotcha but a bit verbose sadly but thanks it should indeed work