Creating cookies in NodeJS application

Creating cookies in NodeJS application

An article about how can we use cookie-parser to add/retrieve cookies in Node application.

What are cookies ?

Cookies are the chunks of small information created by server which are used to track clients activities.

Prerequisites

We must have Express installed in our Node application.

How can we create cookies in Node application ?

To create cookie, we need an external npm package called cookie-parser

We need to install this package in our application.

To install it

  1. Open terminal
  2. Go to your server file(usually app.js) directory
  3. Write this code.
npm install cookie-parser

After installing it we are good to use it in our application, for that we need to write this code in your server file(usually app.js)

//Adding express 
let express = require('express');

//Adding cookie parser
let cookieParser = require('cookie-parser');

//Mounting/calling express function and storing it into app variable
let app = express();

// Using cookie parser as a middleware
app.use(cookieParser());

//Above line will add two new properties, 
//cookies and cookie respectively to request and response objects

//Function to add/retrieve a cookie
function cookieHandler(request,response){
  res.cookie('anyKey':'itsValue'); // This will write cookie to client
  console.log(req.cookies); //This will console log cookies present in client
}

//To use the above function
app.use(cookieHandler);

This is how, we can add and retrieve cookies from client. I hope it will help you.

Happy Coding