ExpressJS Cookies
We offer you a brighter future with industry-ready online courses - Start Now!!
In web development, cookies are a common way to store data on the client-side, and they can be used for a variety of purposes, such as session management, user authentication, and tracking user behavior. In this article, we will explore the basics of cookies in Express.js and how they can be used to enhance the functionality of web applications.
What are Cookies?
Cookies are small text files that are stored on the client-side by a web server. They are used to store data that can be accessed by both the client and the server, and they can be used for a variety of purposes, such as session management, user authentication, and tracking user behavior. Cookies are sent back and forth between the client and server with every request and response, and they are stored in the client’s web browser until they expire or are manually deleted.
Using Cookies in ExpressJS
n Express.js, cookies can be set and retrieved using the cookie-parser middleware. This middleware parses incoming cookie headers and populates the req.cookies object with the key-value pairs of all cookies sent by the client.
To use the cookie-parser middleware, you first need to install it using npm:
npm install cookie-parser
Next, you need to require it in your application and use it as middleware before your routes:
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
Now that the middleware is set up, you can use the res.cookie() method to set a new cookie. This method takes two arguments: the name of the cookie and the value of the cookie.
app.get('/set-cookie', (req, res) => {
res.cookie('username', DataFlair);
res.send('Cookie set!');
});
Output
In this example, we define a new route ‘/set-cookie’ that sets a new cookie called ‘username’ with the value ‘John’. Once the cookie is set, the server sends a response back to the client with the message ‘Cookie set!’.
To retrieve a cookie value, you can simply access the req.cookies object using the name of the cookie:
app.get('/get-cookie', (req, res) => {
const username = req.cookies.username;
res.send(`Hello ${username}!`);
});
Output
In this example, we define a new route ‘/get-cookie’ that retrieves the value of the ‘username’ cookie using the req.cookies object and sends a response back to the client with a personalized message.
Cookie Options in ExpressJS
Cookies can also be configured with various options, such as expiration time, path, and domain. To set these options, you can pass an options object as a third argument to the res.cookie() method.
app.get('/set-cookie', (req, res) => {
res.cookie('username', 'John', { maxAge: 86400000, httpOnly: true });
res.send('Cookie set!');
});
In this example, we set the maxAge option to 86400000 milliseconds (1 day) and the httpOnly option to true, which makes the cookie accessible only through HTTP requests and not through client-side scripts.
ExpressJS Cookies Parser Installation
npm install cookie-parser
The cookie-parser middleware works by parsing the Cookie header of an incoming request and populating a req.cookies object with the cookie key-value pairs. The middleware can also handle signed cookies, where the cookie value is signed using a secret key to prevent tampering.
One of the functions provided by the cookie-parser middleware is JSONCookie(str). This function takes a string representing a JSON object and returns the parsed object. This is useful for cases where a cookie value is a JSON object and needs to be parsed before use.
For example, consider the following cookie value:
user={"name": "John", "age": 30}
To parse this cookie value and retrieve the user’s name, we can use the JSONCookie function as follows:
const cookieParser = require('cookie-parser');
app.use(cookieParser());
app.get('/', (req, res) => {
const user = cookieParser.JSONCookie(req.cookies.user);
const name = user.name;
res.send(`Hello ${name}!`);
});
Output
In addition to JSONCookie, the cookie-parser middleware also provides other functions to handle cookies, such as signedCookies, serialize, and parse. Here’s a brief overview of these functions:
1. signedCookies:
This function is similar to cookies, but it parses signed cookies using the secret key specified in the middleware options. The resulting object is stored in req.signedCookies.
2. serialize:
This function serializes an object into a cookie string. The resulting string can be used to set a cookie in the response headers.
3. parse:
This function parses a cookie string into an object. This is useful for cases where the cookie is received as a string in the request headers, rather than as individual key-value pairs.
Overall, the cookie-parser middleware provides a convenient way to parse and handle cookies in Express.js applications. It simplifies the process of working with cookies, allowing developers to focus on building their application logic instead of dealing with low-level cookie handling.
Deleting Cookies in ExpressJS
To delete a cookie, you can use the res.clearCookie() method, which takes the name of the cookie as an argument.
app.get('/clear-cookie', (req, res) => {
res.clearCookie('username');
res.send('Cookie cleared!');
});
In this example, we define a new route ‘/clear-cookie’ that deletes the ‘username’ cookie using the res.clearCookie() method and sends a response back to the client with the message ‘Cookie cleared!’.
Security Considerations
Cookies can be a powerful tool for web developers, but they can also pose security risks if not properly configured. One of the most common security risks associated with cookies is cross-site scripting (XSS) attacks. This occurs when malicious scripts are injected into a website through vulnerable input fields, such as search boxes or contact forms. To mitigate the risk of XSS attacks, you can set the httpOnly option to true, which prevents client-side scripts from accessing the cookie.
Another security risk associated with cookies is cross-site request forgery (CSRF) attacks, which occur when a malicious website sends a request to a legitimate website on behalf of the user, exploiting their authentication credentials stored in cookies.
To mitigate the risk of CSRF attacks, you can use the csurf middleware in Express.js, which generates and validates unique tokens for each incoming request, ensuring that only legitimate requests are processed.
Conclusion
Cookies are a powerful tool for web developers that can be used for a variety of purposes, such as session management, user authentication, and tracking user behavior. In Express.js, cookies can be easily set and retrieved using the cookie-parser middleware, and they can be configured with various options, such as expiration time, path, and domain. However, it is important to consider the security risks associated with cookies and to configure them properly to prevent XSS and CSRF attacks. With proper configuration and usage, cookies can be a valuable asset in building secure and robust web applications.
Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google


