'Is it possible to set a server-side cookie in Next.js
In my Next.js app, I need to get some parameters from the URL and use them to set a server-side cookie.
But I'm not even sure if I can set a server-side cookie this way. Is this possible at all? If yes, any hint or suggestion would be really appreciate.
Solution 1:[1]
Next applications are not working like usual server applications. Although, you can make a custom flow like using a DBaaS. Or, if you only want to restrict client access to that cookie, I think it's okay to keep them with httponly flag (you should be the one who decides that). In this way, you can only read that cookie at the server.
Here is an example usage with a NextJs serverless API endpoint:
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
const { yourParameter } = req.query;
res.setHeader("set-cookie", `yourParameter=${yourParameter}; path=/; samesite=lax; httponly;`)
res.redirect('/');
}
You can apply the same logic to the getServerSideProps callback or other places that runs at the server.
Solution 2:[2]
use cookies-next by the command npm i cookies-next
Server Side Example
import React from 'react'
import { getCookies, getCookie, setCookies, removeCookies } from 'cookies-next';
const Home = () => {
return (
<div>page content</div>
)
}
export const getServerSideProps = ({ req, res }) => {
setCookies('test', 'value', { req, res, maxAge: 60 * 6 * 24 });
getCookie('test', { req, res});
getCookies({ req, res});
removeCookies('test', { req, res});
return { props: {}};
}
export default Home
Client Side Example
import { getCookies, setCookies, removeCookies } from 'cookies-next';
// we can use it anywhere
getCookies();
getCookie('key');
setCookies('key', 'value');
removeCookies('key');
for more information see https://www.npmjs.com/package/cookies-next
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yunus Emre |
| Solution 2 | Umamad |
