To advertise with us contact on Whatsapp: +923041280395 For guest post email at: itsaareez1@gmail.com

Cookies (cookie-parser) in Node Express Middleware

Cookies (cookie-parser) in Node Express Middleware

Cookie is data which is stored on client’s side which is mostly a browser. Cookies are sent by server request. Whenever a website is loaded, cookies are sent to client side and stored in browser. These are useful in tracking actions of visitor. Cookies are very useful to identify the behaviour of visitor. It helps in providing customized experience to visitors reducing bounce time and increasing engagement with content. These are very helpful in session management to avoid burden on server to entertain login request again and again resulting in enhancement of user friendly experience.

To use cookies in Node Express JS, we will have to import cookie-parser middleware. For installation of cookie-parser, execute the following command on your terminal.

 # npm install --save cookie-parser

How to set cookies in Express JS?

To start using cookies, we will import cookie-parser package in our code. Cookie-parser will parse the cookie header and initializes the request.cookies. The initialized object will have key associated with name of cookie. We will include the cookie code and set a cookie by modifying the index.js file in the following way.

//imports express module
let express = require('express');
//initializes express app
let app = express();
//initialize cookieparser
let cookieParser = require('cookie-parser');
//sets template engine
app.set('view engine', 'pug');
//sets directory name
app.set('views','./views');
//use cookie parser
app.use(cookieParser());
//use middleware to serve static files
app.use('/static', express.static('public'));

app.get('/', function(request, response){
    //the following line sets cookies on client side
    response.cookie('username','LearnCyber').send('Username: LearnCyber');
});

//listens to server at port 3000
app.listen(3000);

Look at the above code, we have imported cookie-parser and initialized it with cookieParser variable and sent the cookie from server to client. To confirm the cookie, open inspect elements and go to Network, visit http://localhost:3000 to set the cookie, now double click localhost page loaded with response 200, you will see the following data. You can see Cookie: username=LearnCyber in Request Headers and Set-Cookie: username=LearnCyber in Response Headers.

node-express-middleware

How to set cookies with expiry headers to speed up your website?

Search Engine Optimization (SEO) is considered to be most important part of any commercial web application or blog. Most of the search engines also consider speed as important factor to rank a website. To speed up the website loading and enhance user friendliness, we will add expiry time of cookies. There are two ways to set expiry time for cookies. One is to use absolute time and other is to use relative time.

We can define maxAge parameter for relative time and expire parameter for absolute time. You can understand from the following code.

//imports express module
let express = require('express');
//initializes express app
let app = express();
//initialize cookieparser
let cookieParser = require('cookie-parser');
//sets template engine
app.set('view engine', 'pug');
//sets directory name
app.set('views','./views');
//use cookie parser
app.use(cookieParser());
//use middleware to serve static files
app.use('/static', express.static('public'));

app.get('/', function(request, response){
    //sets cookie with relative expiry time
    response.cookie(username1, 'Learn', {maxAge: 480000});
    //sets cookie with absolute expiry time
    response.cookie(username2, 'Cyber', {expire: 480000 + Date.now()}); 
});
//listens to server at port 3000
app.listen(3000);

How to delete cookies in Express JS?

We can also delete cookies to avoid tracking and information about customization by using clearCookie(‘name’) function as shown below.

node-express-middleware-1

Leave a Reply

Your email address will not be published. Required fields are marked *