Next.js Discord

Discord Forum

Nextjs API Routes

Unanswered
Polar bear posted this in #help-forum
Open in Discord
Polar bearOP
how do i use cookies in next api routes, ive been reading articles all over the interent and none of the methods are working

28 Replies

which router? App router or pages router?
Polar bearOP
app router
thats pages router
Polar bearOP
oh im sorry i didnt know that
kinda new to next still figuring it out
you can access the cookies with req.cookies in an api route
Polar bearOP
wait but then how do i set the cookies, or create new ones...?
on your response (NextResponse) you can call res.cookies.set
Polar bearOP
oh i have to do it on res, i thought req......
request to read, response to send (new ones)
Polar bearOP
well, you need to make a new response first
Polar bearOP
but then what about the one which comes with the API call
oh nevermind i forgot. The res is a NextApiResponse not a NextResponse.
Polar bearOP
but im using javascript not typescript....
then just remove the types
Polar bearOP
wait but remove the types from where...?
export default function handler(req, res) {
  const testCookie = req.cookies.testCookie;

  if (!testCookie) {
    console.log('Cookie not set yet!');
  } else {
    console.log('Cookie set: ', testCookie);
  }

  res.setHeader('Set-Cookie', 'testCookie="test"; path=/;');
  return res.status(200).send('');
}
Polar bearOP
ohhhh okay
i assume for deleting cookie its just Delete-Cookie instead of Set-Cookie....?
oh yeah taht works
thank you soo much for your help :D
no unfortunately its not. You need to set the expires to a previous date something like that:
  res.setHeader('Set-Cookie', 'testCookie=""; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT');
but you can take a look into the new app router
this makes everything easier