Can't set a cookie using NextJS 9's API Route

12,804

Adapted from offical repo middleware example, you can set Set-Cookie header via res like so:

import { serialize } from 'cookie';

function (req, res) {
   // ...
   // setHeader(headerName: string, cookies: string | string[])
   // can use array for multiple cookies
   res.setHeader('Set-Cookie', serialize('token', 'token_cookie_value', { path: '/' }));
}
Share:
12,804

Related videos on Youtube

Thingamajig
Author by

Thingamajig

Updated on June 04, 2022

Comments

  • Thingamajig
    Thingamajig almost 2 years

    Typically it seems that when using Express, in the "res" object there is "cookie" so you can do something like:

    res.cookie('session', sessionCookie, options);
    

    In the API routes offered by NextJS in Next 9, when looking at res, this does not exist. Is there a way to set the cookie for a response object in a Next API Route function?

  • Afsanefda
    Afsanefda almost 4 years
    how about multiple cookies ? is it working to do that multiple time?
  • Kevin Law
    Kevin Law almost 4 years
    @Afsanefda, you can use array in second param like so: res.setHeader('Set-Cookie', [ serialize('foo', 'bar', { path: '/' }), serialize('hello', 'world', { path: '/' }) ]);
  • Biskrem Muhammad
    Biskrem Muhammad almost 3 years
    hint, if you are using typescript, you should install type definitions as a dev dependency: npm i -D @types/cookie
  • Konrad Grzyb
    Konrad Grzyb almost 3 years
    You can set also HttpOnly cookie with serialize('token', token, { httpOnly: true }) github.com/jshttp/cookie/blob/master/index.js#L91