How to Manage Cookies in Express JS

Updated: December 28, 2023 By: Guest Contributor Post a comment

Introduction

Managing cookies is an essential skill for web developers, especially when dealing with user sessions and personalized content. Express JS, being a popular web framework for Node.js, provides simple mechanisms to handle cookies effectively. This tutorial aims to guide you through the process of managing cookies in Express JS, including setting, getting, and deleting cookies, as well as more advanced topics like signed cookies and cookie options for security.

Setting Up Express

Before diving into cookies, let’s set up a basic Express application. You’ll need to have Node.js installed on your machine.

const express = require('express');
const app = express();

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

Setting Cookies

To set cookies in Express, use the ‘response.cookie()’ method. Here’s an example:

app.get('/set-cookie', (req, res) => {
    res.cookie('username', 'JohnDoe');
    res.send('Cookie is set');
});

Getting Cookies

To access cookies sent by the client, you’ll need to use a middleware like ‘cookie-parser’. Install it using npm:

npm install cookie-parser

Then, include it in your Express app:

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

Now you can read cookies from the request object:

app.get('/get-cookie', (req, res) => {
    const username = req.cookies['username'];
    res.send(`Username from cookie: ${username}`);
});

Deleting Cookies

Delete cookies using the ‘response.clearCookie()’ method:

app.get('/clear-cookie', (req, res) => {
    res.clearCookie('username');
    res.send('Cookie username cleared');
});

Signed Cookies

To increase security, you can also use signed cookies in Express. First, you need to set a secret key:

app.use(cookieParser('your_secret_key'));

Then, set a signed cookie:

app.get('/set-signed-cookie', (req, res) => {
    res.cookie('signed_username', 'JohnDoe', { signed: true });
    res.send('Signed cookie is set');
});

Get a signed cookie like this:

app.get('/get-signed-cookie', (req, res) => {
    const signedUsername = req.signedCookies['signed_username'];
    res.send(`Signed username from cookie: ${signedUsername}`);
});

Cookie Options for Security

Express allows you to set various cookie options to enhance security:

app.get('/set-cookie-with-options', (req, res) => {
    res.cookie('secure_cookie', 'value', { httpOnly: true, secure: true, sameSite: 'strict' });
    res.send('Secure cookie with options is set');
});

Conclusion

In this tutorial, you’ve learned how to manage cookies in an Express JS application. We’ve covered the basics of setting, getting, and deleting cookies, as well as more advanced aspects including signed cookies and security options. Remember that cookies are a powerful tool for state management in web applications, but they should be used wisely and securely.