Sling Academy
Home/Node.js/How to Manage Cookies in Express JS

How to Manage Cookies in Express JS

Last updated: December 28, 2023

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}`);
});

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.

Next Article: Node.js & Express: Implementing Route Guards with Middleware (3 Ways)

Previous Article: How to Download a File from NodeJS Server using Express

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates