Express Cookie-Parser – Signed and Unsigned Cookies

A cookie is a piece of data that is sent to the client-side with a request and is stored on the client-side itself by the Web Browser the user is currently using. With the help of cookies –

  • It is easy for websites to remember the user’s information
  • It is easy to capture the user’s browsing history
  • It is also useful in storing the user’s sessions

The session makes requests to all the servers using a secret Id. The information is stored on the server that is linked to this secret ID.
To make use of cookies in our application, cookie-parser middleware is used. To install it, write the following command –

npm install cookie-parser@latest --save

Also, to install express middleware write the following command –

npm install express@latest --save

These commands will install the latest versions of cookie-parser and express.
Cookie-parser middleware is used to parse the cookies that are attached to the request made by the client to the server. Therefore, to use cookie-parser, we will write the following lines of code in our JavaScript file –

filter_none

edit
close

play_arrow

link
brightness_4
code

const cookieParser = require('cookie-parser');
const express = require('express')
  
const app = express();
app.use(cookieParser());

chevron_right


Let’s look at an example of how to setup a new cookie. Create a new file named “index.js”. For setting up and assigning a name to a cookie, follow the code –



filter_none

edit
close

play_arrow

link
brightness_4
code

const express = require('express');
const cookieParser = require('cookie-parser');
  
const app = express();
  
app.get('/', (req, res) => {
   res.cookie('name', 'GeeksForGeeks').send('Cookie-Parser');
});
  
app.listen(3000, (err) => {
    if(err){ console.log(err) } 
    else { console.log('Success!!') }
});

chevron_right


Here, we sent the cookie to the new route and set the name of the cookie as ‘GeeksForGeeks’. In the last block of code, our server is listening to the port 3000 with a callback function. If there will be an error then the callback function will return the error else it will return “Success”.
Now, run the following code with the command –

node index.js

To check if the cookie is set or not, just go to this link after successfully setting up the server. Open the console and write the command as –

document.cookie

You will get the output as –

"name=GeeksForGeeks"

Also, the cookie-parser middleware populates the req.cookies with name that is sent to the server. Here, in our case, we can add the following line of code in our route –

console.log(req.cookies)

The output of the above line will be –

{ name: 'GeeksForGeeks' }

Methods for cookie-parser

  • cookieParser(secret, options)
  • – This middleware takes two parameters. First one will be the secret Id and other will the options. The secret Id can be a string or an array of strings. If the secret parameter is not provided then it will take the cookie as unsigned cookie. Therefore, it is optional to provide the secret ID. The second parameter will be an object specifying what actions to be taken with the cookies. For example, decode is a function to decode the value of the cookie.

  • cookieParser.JSONCookie(str)
  • – This method will parse the value of the cookie as a JSON cookie. It will return the parsed JSON value if the cookie provided is a JSON cookie. If not a JSON cookie, it will return the passed value itself.

  • cookieParser.JSONCookies(cookies)
  • – Provided an object with its Id attached. This method will iterate over the Object Id’s provided and will call the “JSONCookie” on each value. It will replace the original value with the parsed value. This will return the same object that was passed in.

  • cookieParser.signedCookie(string, secret)
  • – This method parses the cookie as a signed cookie. If the cookie is a signed cookie and signature can be validated, then it will return the parsed unsigned value. If the cookie is unsigned, then the original value is returned. If the cookie is signed but the signature cannot be validated, then false is returned.
    Now, our second argument secretcan be a string or an array of strings. If it is a string, then it will be used as a secret. If it is an array, then iteration over each element of the array will be done and the cookie will be unsigned using each secret.

  • cookieParser.signedCookies(cookies, secret)
  • – This method will perform the iteration over each ID and check if any ID is a signed cookie. If it is signed and the signature can be validated, then the ID will be deleted from the object will it will be added to the new returning object.

Depending on the type of the cookie sent from the client, these methods will automatically be called.

Implementation of Signed and Unsigned Cookie

Unsigned Cookie
filter_none

edit
close

play_arrow

link
brightness_4
code

const express = require('express');
const cookieParser = require('cookie-parser');
  
const app = express();
  
app.get('/', (req, res) => {
   res.cookie('name', 'GeeksForGeeks').send();
   console.log(req.cookies);
  
});
  
  
app.listen(3000, (err) => {
    if(err){ console.log(err) } 
    else { console.log('Success!!') }
});

chevron_right


The output for the above code will be –

"name=GeeksForGeeks"
Signed Cookie
filter_none

edit
close

play_arrow

link
brightness_4
code

var express = require('express')
var cookieParser = require('cookie-parser')
   
var app = express()
app.use(cookieParser('GFG'))
   
app.get('/', function (req, res) {
  res.cookie('name', 'GeeksForGeeks', { signed: true }).send();
  console.log(req.signedCookies)
})
   
app.listen(3000, (err) => {
  if(err) { console.log(err) }
  else { console.log('Success') }
})

chevron_right


Here, In the 4th line – “GFG” is provided as a secret value to the cookie.
In the 7th line – the name for the cookie is set to “GeeksForGeeks” and the object signed is set to true.
The output for the above code will be –

{ name: 'GeeksForGeeks' }

full-stack-img




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.