Express Cookie-Parser – Signed and Unsigned Cookies
Last Updated :
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' }
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
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"
Signed Cookie
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' }
Similar Reads
How to manipulate cookies by using âResponse.cookie()â in Express?
Cookies are small data that is stored on the client's computer. Using this cookie various tasks like authentication, session management, etc can be done. In Express JS we can use the cookie-parser middleware to manage the cookies in the application. In this article, we going to manipulate cookies in
3 min read
How to Set, View and Manipulate Cookies using 'Response.cookie()' and Postman ?
Cookies enable websites to store small pieces of information on a user's device. It helps enhance user experience and enable various functionalities. In this article, we'll explore a simple way to manipulate cookies using the 'Response.cookie()' function Prerequisite:Basics of NodejsBasics of Expres
2 min read
Difference between req.cookies and req.signedCookies in Express.js
req.cookies: Request. Cookies are supposed to be cookies that come from the client (browser) and Response. Cookies are cookies that will send back to the client (browser). Cookies are small files/data that are sent to the client with a server request and stored on the client side. This helps us to k
3 min read
How to Manage Sessions and Cookies in Express JS?
Express is a small framework that sits on top of NodeJS web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your applicationâs functionality with middleware and routing. It adds helpful utilities to NodeJS HTTP objects, it helps the rendering of
4 min read
How to set and unset cookies using jQuery?
An HTTP cookie is a small piece of data sent from a server and stored on client-side by the browser itself, Cookies are made to keep track of user and also to provide one nice browsing experience. We can also set our own cookies in the browser according to our need. Cookies can be set in the browser
2 min read
Difference between sessions and cookies in Express
Express.js is a popular framework for Node.js, that is used to create web applications. It provides tools to manage user sessions and cookies. The session and cookies are used to maintain the state and manage user authentication. In this article, we will learn about what sessions and cookies in Expr
4 min read
Express.js req.cookies Property
The req.cookies property is used when the user is using cookie-parser middleware. This property is an object that contains cookies sent by the request. Syntax: req.cookiesParameter: No parameters. Return Value: Object Installation of the express module: You can visit the link to Install the express
2 min read
Why are HTTP cookies used by Node.js for sending and receiving HTTP cookies?
The HTTP protocol is one of the most important protocols of the Application layer of the OSI model. The main use of this protocol is for sending hypertext information to the client to the server and server to the client to communicate on the World Wide Web. But, the HTTP protocol is a stateless prot
5 min read
Difference Between Session and Cookies
When building a website, we need to remember user information whether it's login details, preferences, or shopping cart items. Two common ways to store this data are sessions and cookies. Cookies are small pieces of data stored in the user's browser. They help remember things like login status or pr
7 min read
Express res.cookie() Function
The res.cookie() function is used to set a cookie in the client's browser. It allows you to assign a cookie by providing a name and a value. The value can be a simple string or an object, which will be automatically converted to JSON. Syntax: res.cookie(name, value [, options])name: The name of the
3 min read