1 | initial version |
You can set cookies in Next.js while using Node.js (Express) as the backend by installing the cookie-parser
middleware in the Express server and using the res.cookie()
method to set the cookie.
Install the cookie-parser
middleware:
npm install cookie-parser
Require the cookie-parser
middleware in the Express server:
const cookieParser = require('cookie-parser');
const express = require('express');
const app = express();
Use the cookie-parser
middleware in the Express server:
app.use(cookieParser());
Set a cookie in the Next.js server by sending a request to the Express server:
// In the Next.js server
fetch('/api/set-cookie', {
method: 'POST',
body: JSON.stringify({ name: 'myCookie', value: '123' }),
});
// In the Express server
app.post('/api/set-cookie', (req, res) => {
const { name, value } = req.body;
res.cookie(name, value);
res.send('Cookie set successfully!');
});
Retrieve the cookie in the Next.js server:
const cookies = parseCookies(req);
const myCookie = cookies.myCookie;
function parseCookies(req) {
const cookie = req.headers.cookie;
const cookies = {};
if (cookie) {
cookie.split(';').forEach((c) => {
const [key, value] = c.trim().split('=');
cookies[key] = value;
});
}
return cookies;
}