Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 589
Thingamajig Avatar asked Aug 19 '19 14:08

Thingamajig


2 Answers

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: '/' }));
}
like image 94
Kevin Law Avatar answered Oct 21 '22 13:10

Kevin Law


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

Client Example

import { getCookies, setCookie, deleteCookie } from 'cookies-next';

// we can use it anywhere

getCookies();
getCookie('key');
setCookie('key', 'value');
deleteCookie('key');

Server example

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 });

notice the difference in client and server. For server side, you must pass { req, res } to the next-cookie, else it won't work

like image 1
Chukwuemeka Maduekwe Avatar answered Oct 21 '22 13:10

Chukwuemeka Maduekwe