Reputation: 391
In getServerSideProps I need to set multiple cookies on client device. I coded:
Upvotes: 21
Views: 19297
Reputation: 577
If you're using next js v14.x, here's how you can do it on the server side(route handler)
import { cookies } from "next/headers";
// Cookies values should take the format below
const allCookies = {
'cookie_name': {
value: 'cookie_value'
options: {/*...cookie_options*/ }
}
}
...
Object.entries(allCookies).map(([name, { value, options }]) => {
cookies().set(name, value, options);
});
Upvotes: 0
Reputation: 562
res.setHeader('Set-Cookie', [
cookie.serialize(
'access', user.tokens.access, {
httpOnly: true,
secure: process.env.NODE_ENV !== 'development',
maxAge: 60 * 30,
sameSite: 'strict',
path: '/api/'
}
),
cookie.serialize(
'refresh', user.tokens.refresh, {
httpOnly: true,
secure: process.env.NODE_ENV !== 'development',
maxAge: 60 * 60 * 24,
sameSite: 'strict',
path: '/api/'
}
)
]);
Upvotes: 4
Reputation: 6422
You can likely use an array for the second argument.
ctx.res.setHeader('set-cookie', ['access-token=1', 'refresh-token=1'])
In Next.js, the req
and res
objects are just Node.js HTTP objects. So anything you can do in Node.js you can do with Next.js.
https://nodejs.org/api/http.html#http_response_setheader_name_value
Upvotes: 33
Reputation: 567
Since the res.setHeader
function in the NextJS context variable is just a NodeJS http
module Response object, you can set multiple values for a header like so:
res.setHeader('set-cookie', ['val1', 'val2'];
This behavior is documented here in the NodeJS docs:
Use an array of strings here to send multiple headers with the same name.
Upvotes: 9