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;
}
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-05-02 11:00:00 +0000
Seen: 10 times
Last updated: Dec 06 '21
How can I use GlowCookies for Google Adsense to comply with GDPR?
Can I change the message from the GlowCookies banner in the Configuration?
What are the steps for conducting a precise search and filter using sequelize in node.js?
What is the method for creating an HTTP POST request using node.js?
How can I install Mongoose to my Node.js project using NPM?
How can I migrate all UFW Firewall Rules from one Ubuntu Server to another one?
How can I insert a Cookie in the Nginx Configuration File?
How can the SvelteKit/Pocketbase application be deployed to a Linode server?
What is the method for placing parentheses in column names when creating a table using an SQL query?