Next.js Discord

Discord Forum

Cookies in Nextjs middleware

Answered
Britannia Petite posted this in #help-forum
Open in Discord
Britannia PetiteOP
Is it possible to set cookies inside of middleware.js on request and access them in page.js ?

If I log cookie value inside of middleware, it logs it fine so it is set successfully.
When I try to log it in page.js every cookie except the one I set in middleware is present.

what is going on ?
Answered by Ray
try this
 const resp =  NextResponse.next()
 resp.cookies.set('cookie', 'value')
 return resp;
View full answer

15 Replies

Britannia PetiteOP
request.cookies.set('lang', 'ba')
@Britannia Petite request.cookies.set('lang', 'ba')
try this
 const resp =  NextResponse.next()
 resp.cookies.set('cookie', 'value')
 return resp;
Answer
Britannia PetiteOP
But what happens with request ?
It works. But

function middleware(request) {
  const res = NextResponse.next()
 res.cookies.set('lang', 'ba')
  return res
}


seems like request is not used for anythign here ? what if it has some more informations ?
you can read the cookie from request if you need
Britannia PetiteOP
Now I understand some things regarding middleware.

Thanks Ray
@Ray if you want to set the cookie, and access it on the page, you should set it on the response
Dogue Brasileiro
what's the purpose of setting cookies on the request then?
@Dogue Brasileiro what's the purpose of setting cookies on the `request` then?
well, you could set the cookies on request and read it on the page later like this
  request.cookies.set("hello", "1");
  return NextResponse.next({ request });

but it will not persist because the cookies need to set on the response and send to client browser
Dogue Brasileiro
  request.cookies.set("hello", "1");
  return NextResponse.next({ response: request });
Dogue Brasileiro
ok so there's not much use for setting cookies on request