Sometimes, we want to set cookie in Node.js using the Express framework.
In this article, we’ll look at how to set cookie in Node.js using the Express framework.
How to set cookie in Node.js using the Express framework?
To set cookie in Node.js using the Express framework, we can use the res.cookie
method.
For instance, we write
app.use(express.cookieParser());
app.use((req, res, next) => {
const cookie = req.cookies.cookieName;
if (!cookie) {
const randomNumber = Math.random().toString();
res.cookie('cookieName', randomNumber, {
maxAge: 900000,
httpOnly: true
});
console.log('cookie created successfully');
} else {
console.log('cookie exists', cookie);
}
next();
});
to call express.cookieParser
to return the cookie parser middleware.
Then we call app.use
to use it.
Then we call app.use
again with a callback that checks if the cookie with key cookieName
exists.
If it does, then we call res.cookie
with the cookie key and value, and an object with the maxAge
of the cookie in seconds to return the cookie with the response.
Then we call next
so the next middleware can be called.
Conclusion
To set cookie in Node.js using the Express framework, we can use the res.cookie
method.