Cookies are simple files that are stored on user’s computer.It stores the data in a text file. This helps us to keep track of the user action. Cookies can be accessed either by the web server or client computer. This allows the server to deliver a page to a particular user, or the page itself can be stored some script which is aware of the data in the cookie and so is able to carry information from one visit to the website or related site to the next.
The following are the various uses of the HTTP Cookies:-
- Session management
- Personalization(Recommendation systems)
- User tracking
Topics Covered:-
- Introduction.
- What’s in a cookie?
-
Why are Cookies Used?
-
Installation.
-
Adding cookies.
- Adding Cookies with Expiration Time.
- Deleting Cookies.
What’s in a cookie?
Each cookie is finally small lookup table involves pairs of key-values – for example (first name, Steve) (last name, jobs). Once the cookie has been read by the code on server or client computer, the data can be restored and used to customize the web page accordingly.
Why are Cookies Used?
Cookies are an adequate way to carry data between sessions on a website, without loading a server machine with huge amounts of data storage.If we store data on a server without cookies it would be insecure and inconvenient because then it will get difficult to restore users data without requiring a login on each visit to the website.
Installation:-
To use cookies with express, firstly we have to install cookie-parser middleware.To install it, use the following command-
npm install cookie-parser --save
Now to use cookies with express, we will have to require the cookie-parser module. Cookie-parser is a middleware which parses cookies to attach with the client request object.
var cookieparser = require(‘cookie-parser’);
app.use(cookieparser());
Define a route:-
Multiware cookie-parser parse the cookie header and then populate req.cookies with an object by cookie name.
To set new cookies first we have to define a route and for this follow the below example:-
app.get(‘/’,function(req,res) {
res.cookie(‘mycookie’,'express');
res.end(‘cookies inserted…’);
});
Adding cookies
To use a new cookie, first define a new route in your express.js app like:-
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
app.use(cookieParser());
app.get('/', function(req, res) {
res.cookie('mycookies', 'express')
.send('cookie set');
});
app.listen(3000, function(err, message) {
console.log("server start......")
});
Browser always sends back cookies every time it queries the server. To view cookies from your server, add the following console to that route.
console.log(‘cookies:’ ,req.cookies)
You will get the output like this:-
Cookies: {mycookies: ‘express’ }
Can I see/view the cookies on my computer?
Yes, Most of the available browsers have a configuration screen which allows the user to view where and what cookies have been stored on the user computer, and if we want we can delete them as well.
To see the cookie on your computer browser (if you are using Google Chrome) follow the given step:-
chrome://settings/content/cookies
It’s not possible for a webpage to see cookies set by other sites, as this would show privacy and security problem.
How Long Does a Cookie Store?
The time of expiry of a cookie can be set when the cookie is created.If time is not set by the user then by default, the cookie is destroyed when the current browser window is closed.
Adding Cookies with Expiration Time:-
You can add cookies that expire. Just pass an object with property ‘expire’ and set to the time when you want it to expire from your browser. Following is an example of this method.
//Expires after 360000 ms from the time it is set.
res.cookie(name, 'value', {expire: 360000 + Date.now()});
The other way to set the expiration time is using ‘maxAge’ property. By using this property, we can provide relative time rather of absolute time. Following is an example of this method.
//This cookie also expires after 360000 ms from the time it is set.
res.cookie(name, 'value', {maxAge: 360000});
Delete existing cookies:-
To delete a cookie, use the clearCookie function. You need to define a route in your express.js app.Use the following code to delete an existing cookie in your browser:-
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
app.use(cookieParser());
app.get('/remove', function(req, res) {
res.clearCookie('mycookies', { expires: new Date(), path: '/' });
res.send('cookie deleted');
console.log(Date())
});
app.listen(3000, function(err, message) {
console.log("server start......")
});
Learn More: