A cookie is a mechanism that allows the server to store its own information about a user on the user's own computer. You can view the cookies that have been stored on your hard disk (although the content stored in each cookie may not make much sense to you). The location of the cookies depends on the browser.
To use cookies in nodejs express application, we use cookie-parser package of npm, By using this package we can easily manage the express application cookies.
npm install cookie-parser
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
// adding cookieParser to middleware stack
app.use(cookieParser());
The module gives us access to req.cookies with an object keyed with the cookie name. We can also enable signed cookie support by passing a secret string, Which assigns req.secret.
In the above code, We have set the maximum age of a Cookie, Which is optional. We can also set the expire time in milliseconds like below
We can also set cookie only over HttpOnly.This flag tells the browsers to not allow client-side script access to the Cookie.
res.cookie(cookie_name , 'cookie_value', { HttpOnly: true});
We can tell express to use https encrypted channel to exchange cookie data with secure
flag.
We can access Cookies via request object, req.cookies.cookie_name
or req.cookies
.
W can also easily delete Cookies by using res.clearCookie function, which accepts the name of the Cookie which we want to delete. W can also delete Cookies from browser developers tools.
So in this article, We learn all about cookies in Node.js express application.
That’s all for now. Thank you for reading and I hope this article will be very helpful to understand how to handle cookies in node.js express application.
Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.