Express Cookie-Parser – Signed and Unsigned Cookies


We can use cookies to store the user information on the client side in the web browser. For example, whenever a user opens any website in the browser, it requests some information to the server, and once the client gets the information, it stores it in the browser with the expiry time.

It makes the website faster for users, as it doesn’t need to request the server for information every time users come back to the site. However, once cookies expire, the client requests the server again for that information.

In this tutorial, we will learn about the express cookie-parse npm package and how to set cookies on the client’s web browser.

Use the cookie-parser NPM package to set and fetch cookies

Users can follow the steps below to create a node project.

  • Step 1 − First, users need to download and install the Node Js on the local computer.

  • Step 2 − Create a new folder for the project and open the terminal in that directory.

  • Step 3 − To start the new node project, enter the below command in the terminal in the project directory.

npm init -y
  • Step 4 − Now, users need to install the required npm packages. The first package required is express, and another one is cookie-parser. Users can execute the below command to download the npm package to the current project.

npm i express cookie-parser
  • Step 5 − Next, we need to set up the server code for a node server.

Users can create a new server.js file in the project directory and add the code below.

// importing the express package
const express = require("express");

// using the express for app
const app = express();
app.get("/", (req, res) => {
   res.send("Welcome to the new server!");
});

// setting up the port for the server
app.listen(5000, (err) => {
   console.log("Server started successfully on port 5000");
});
  • Step 6 − Now, users need to run the project and to do so, users can enter the below command in the terminal.

node server.js

The server is started successfully, and when users go to the http://localhost:5000/ URL, they can see the output below.

We have set up the node project. We need to write a code to use the cookie parser NPM package for signed and unsigned cookies.

Methods of cookie-parse package

Before we start writing the code for cookies using the cookie parser, let’s understand the method it contains.

cookieParser(key, cookieOptions)

Users can use the cookieParser() method to create a new middleware. It takes a secret key and cookie options as a parameter; however, both are optional. If we pass a secret key, it parses the cookie as a signed cookie; otherwise, as an unsigned cookie.

Also, users can use the request.cookie to parse unsigned cookies and request.signedCookies to parse the signed cookies.

cookieParser.JSONCookie(string)

If we set a JSON object as a cookie, JSONCookie() method returns the JSON object; otherwise, normal string value.

cookieParser.JSONCookies(Cookies_to_store)

The Cookies_to_store is an object. So, when we pass the object as a parameter of the JSONCookies() method, it iterates through every key-value pair of the object, parses the value for every key, and replaces it with the parsed value.

cookieParser.signedCookie(string, key)

We can use the signedCookie() method to get the parsed unsigned cookie. If the key is invalid, the method raises an error. Also, if the cookie is not signed, the method returns the normal unsigned value.

cookieParser.signedCookies(Cookies_to_store, key)

Here, again Cookies_to_Store is an object, and users can use the signedCookies() method to iterate over every value of the object and parse signed cookies for every value if the secret key is valid. It returns a new object of cookies with the parsed values.

Note − Users can see the cookie output only if the server is in production mode. Also, users can use the online nodeJS editor to see the output.

Example – unsigned cookies

In the example below, we send cookies to the browser without using the cookie-parser middleware. We have used the send() method to send cookies to the browser.

const express = require("express");
const parser = require("cookie-parser");
const app = express();
app.get("/cookie", (request, response) => {

   // sending the unassigned cookies
   response.cookie("message", "This is a cookie.").send();
   console.log("The cookies are " + request.cookies);
});
app.listen(5000, (err) => {
   console.log("Server started successfully on port 5000");
});

Example - signed cookies

In the example below, we have used the cookie-parser middleware to generate signed keys. Users can see how we have initialized the middleware with the secret_key. After that, we added the {signed: true } object as a parameter of the cookie() method to send signed cookies.

const express = require("express");
const parser = require("cookie-parser");
const app = express();

// Initializing the middleware with a secret key
app.use(parser("secret_key"));

app.get("/cookie", (request, response) => {
   // sending the signed cookies
   response
   .cookie("message", "This is a singed cookie", { signed: true })
   .send();
   
   // using the signedCookies property to access cookies
   console.log("The cookies are " + request.signedCookies);
});
app.listen(5000, (err) => {
   console.log("Server started successfully on port 5000");
});

We learned to send signed and unsigned cookies in this tutorial. The secret key is the main difference between the signed and unsigned cookies. We provide a secret key with the signed cookies, and we need to use it to access them.

To set unsigned cookies, users don’t need to use the cookie parser as a middleware with the secret key.

Updated on: 17-Mar-2023

838 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements