Express Cookie-Parser - Signed and Unsigned Cookies - GeeksforGeeks

28 May, 2020
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 –
const cookieParser = require('cookie-parser');const express = require('express')  const app = express();app.use(cookieParser());
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 –
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!!') }});
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' }
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.
– 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.
– 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.
– 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.
– 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.
– 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.
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!!') }});
The output for the above code will be –
"name=GeeksForGeeks"
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') }})
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' }
Node.js-Misc
JavaScript
Node.js
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.readFile() Method
How to update NPM ?