Tuesday 6 June 2017

How to use cookies with expressJS in node.js

How to use cookies with expressJS in node.js

Question: What is cookies in NodeJS?
Cookies is a node.js module for getting and setting HTTP(S) cookies.


Question: How to install cookies?
npm install cookie-parser       



Question: How to setup cookie with expressJS?
var express = require('express');
var cookieParser = require('cookie-parser');

var app = express();
app.use(cookieParser());
     



Question: What are the feature of cookie?
  1. Lazy: Since cookie verification against multiple keys could be expensive, So cookies are verified lazily.
  2. Secure: All cookies are httponly by default and cookies sent over SSL are secure by default.
  3. Unobtrusive: Signed cookies are stored the same way as unsigned cookies, instead of in an obfuscated signing format.
  4. Agnostic: This library is optimized for use with Keygrip, but does not require it.



Question: How to set cookies?
app.get('/set-cook', function(req, res) {
       //Set the cookie
      var c_name='cookie_name';        
      res.cookie(c_name, 'cookie value');
      
      //Send Response
      res.send('cookie value');
});
Note above wll work with expressJs only.
Question: How to get cookies?
app.get('/get-cook', function(req, res) {        
    //Get cookie name
      var cookieValue=req.cookies.cookie_name; 

      //Send Response
      res.send('Cookie name is '+cookieValue);
});
Note above wll work with expressJs only.



Question: How to delete cookies?
app.get('/delete-cook', function(req, res) {        

    //Delete the cookie
     clearCookie(cookie_name);

      //Send Response
      res.send('Cookie name is '+cookieValue);
});
Note above wll work with expressJs only.



Question: How to set expiration time for cookie?
res.cookie(name , 'value', {expire : new Date() + 600}); //10 minutes

res.cookie(name , 'value', {expire : new Date() + 3600}); //1 hour

res.cookie(name , 'value', {expire : new Date() + 18000}); //5 hour



Question: What are HTTP cookies?
HTTP cookies are small pieces of data that are sent from a website and stored in your browser. With use of cookies we maintain the login and track the user activities. Cookies are very valuable to better user experience. Following are the three main use of cookies.
  1. Session management
  2. Personalization
  3. Track the user activites



Question: Why we must use Cookie-Free Domains for static contents?
Cookies are very useful in website. But while access static contents of website like CSS, image and JS then there is no use of cookie. Means while Browser is accessing the static file, Server should send the static content without use of cookie. It will improve the website performance.