You can use the res.cookie() method to set a cookie
Step 1: Install Express
If you don't have Express installed, add it to your project:
npm install express
Step 2: Basic Code to Set a Cookie
The res.cookie() method allows you to define a cookie with a name, value, and optional configurations.
const express = require('express');
const app = express();
app.get('/set-cookie', (req, res) => {
// Setting a cookie with a name and value
res.cookie('username', 'Mahak', {
maxAge: 60000, // 1 minute
httpOnly: true, // Makes the cookie inaccessible to JavaScript on the client side
secure: false, // Set true for HTTPS
sameSite: 'strict' // Controls cross-site behavior
});
res.send('Cookie has been set!');
});
app.get('/get-cookie', (req, res) => {
// Access cookies using req.cookies (requires cookie-parser)
res.send(`Cookie value is: ${req.cookies?.username || 'cookie not found'}`);
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});