Cookies are one of the important recipe for building an effective web application.
A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is a small piece of data sent from a website you are surfing and stored in a user/client computer. Every time the user loads that website again, the browser sends this cookie back to the server to notify the website of the user’s previous activity.
This way, using cookie, we could track user activities like her navigational behaviors, previous purchases on our site or previous leads etc.
Setting Cookie in Express: Node.js
app.js
1 2 3 4 5 6 7 8 9 10 | var express = require('express'); var app = express(); app.use(express.cookieParser()); app.get('/user/:user', function(req, res){ res.cookie('username', req.params.user) .send('<p>Cookie Set: <a href="/user">View Here</a>'); }); </p> |
Using express’s cookieParser() middleware we can enable working with cookies.
Once the user navigates to /user/someUserName URL, the cookie is set with the name username and the value is actually fetched out of the request object’s params.
General Syntax for setting Cookie
res.cookie('cookieName', value, {expires: new Date() + 99999, maxAge: 99999}); |
Set a name to the cookie, give it some value. Also you can set the optional settings like, expiration date or the maxAge the cookie will be alive on the client computer.
Accessing Cookie in Express: Node.js
app.js
1 2 3 | app.get('/user', function(req, res){ res.send(req.cookies.username); }); |
Once the user visits /user route, we fetch the value present in the req.cookies.username and display it to the user.
Cookie In Express: Node.js
[youtube https://www.youtube.com/watch?v=mdvQ74KL-fU]
Note: We could see the value stored in a cookie, by using chrome’s console window and typing document.cookie
Clearning Cookie in Express: Node.js
app.js
1 2 3 4 | app.get('/user', function(req, res){ res.clearCookie('username') .send(req.cookies.username); }); |
You could remove a cookie by using clearCookie method of response object.
Once the cookie has been removed, you can set it again explicitly using Chromes console window.
Type: document.cookie = “username = Microsoft”
now refresh the browser, and you’ll see Microsoft being displayed!
Thanks for your tutorial. It doesn’t work in latest express.js (4.2.0). The browser just hang. Any idea?
My code is:
var express = require(‘express’);
var router = express.Router();
var cookieParser = require(‘cookie-parser’);
router.use(cookieParser);
router.get(‘/:name’, function(req, res) {
console.log(‘here’);
res.send(req.param.name);
//res.cookie(‘name’,req.param.user)
// .send(‘Cookie Set:View Here‘);
});
router.get(‘/’, function(req, res) {
res.clearCookie(‘name’)
.send(req.cookie.name);
});
module.exports = router;
It hangs in router.use(cookieParser);
I found the problem. It’s my problem. Thanks again.