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: '/' }));
}
Related videos on Youtube
Author by
Thingamajig
Updated on June 04, 2022Comments
-
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 almost 4 yearshow about multiple cookies ? is it working to do that multiple time?
-
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 almost 3 yearshint, if you are using typescript, you should install type definitions as a dev dependency:
npm i -D @types/cookie
-
Konrad Grzyb almost 3 yearsYou can set also HttpOnly cookie with serialize('token', token, { httpOnly: true }) github.com/jshttp/cookie/blob/master/index.js#L91