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?
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: '/' }));
}
I just found an easier way to do this in Next.js, though with a library -- cookie-next
run npm install --save cookies-next
If you are using next.js version greater than 12.2.0 you need to use cookies-next version 2.1.0 or later
import { getCookies, setCookie, deleteCookie } from 'cookies-next';
// we can use it anywhere
getCookies();
getCookie('key');
setCookie('key', 'value');
deleteCookie('key');
getServerSideProps or pages/api
import { getCookies, getCookie, setCookie, deleteCookie } from 'cookies-next';
export default async function handler(req, res) {
setCookie('server-key', 'value', { req, res, maxAge: 60 * 60 * 24 });
getCookie('key', { req, res });
getCookies({ req, res });
deleteCookie('key', { req, res });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With