Express.js / Express.js with Sessions and Cookies

Cookie Management

This tutorial will guide you through managing cookies in Express.js. We'll cover creating, reading, updating, and deleting cookies to maintain state between requests.

Tutorial 2 of 4 4 resources in this section

Section overview

4 resources

Explores managing sessions and cookies in Express applications.

1. Introduction

In this tutorial, we aim to guide you through managing cookies in Express.js. Cookies are a critical part of maintaining state between server and client requests. By the end of this tutorial, you will be able to create, read, update, and delete cookies using Express.js.

Before beginning, you should have a basic understanding of JavaScript, Node.js, and Express.js.

2. Step-by-Step Guide

Express.js doesn't handle cookies by default, we need to use a middleware called cookie-parser.

First, install cookie-parser:

npm install cookie-parser

After installing cookie-parser, we can include it in our application:

const express = require('express');
const cookieParser = require('cookie-parser');

const app = express();
app.use(cookieParser());

Now we are ready to manage cookies.

Creating Cookies

You can create cookies using the response.cookie() function. This function accepts three parameters: cookie name, cookie value, and options object.

app.get('/set', (req, res) => {
   res.cookie('cookieName', 'cookieValue', {expire: 360000 + Date.now()});
   res.send('Cookie is set');
});

Reading Cookies

Cookies can be read from the request.cookies object.

app.get('/get', (req, res) => {
   res.send(req.cookies);
});

Updating Cookies

Updating a cookie can be done by setting the cookie again with the new value.

app.get('/update', (req, res) => {
   res.cookie('cookieName', 'newCookieValue', {expire: 360000 + Date.now()});
   res.send('Cookie updated');
});

Deleting Cookies

You can delete cookies using the response.clearCookie() function.

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

3. Code Examples

Here is a complete example demonstrating all the actions we can perform on cookies.

const express = require('express');
const cookieParser = require('cookie-parser');

const app = express();
app.use(cookieParser());

// Set a new cookie
app.get('/set', (req, res) => {
   res.cookie('myCookie', 'express', {expire: 360000 + Date.now()});
   res.send('Cookie has been set');
});

// Get all cookies
app.get('/get', (req, res) => {
   res.send(req.cookies);
});

// Update a cookie
app.get('/update', (req, res) => {
   res.cookie('myCookie', 'updatedExpress', {expire: 360000 + Date.now()});
   res.send('Cookie has been updated');
});

// Clear a cookie
app.get('/clear', (req, res) => {
   res.clearCookie('myCookie');
   res.send('Cookie has been cleared');
});

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

4. Summary

In this tutorial, we have covered how to manage cookies in Express.js. We learned how to create, read, update, and delete cookies using cookie-parser middleware.

To continue learning, you can explore more about cookie options like HttpOnly, Secure, Domain, Path, and SameSite.

Additional resources:
- Express.js Documentation
- MDN Web Docs on HTTP Cookies

5. Practice Exercises

  1. Create an Express.js server that sets a user's name in a cookie.
  2. Update the previous exercise to display a welcome message to the user using the value in the cookie.
  3. Create an Express.js server that sets a counter in a cookie. Every time a user visits the site, increment the counter.

Solutions and explanations will be provided upon request. You can explore more about cookies and their options for more practice.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Date Difference Calculator

Calculate days between two dates.

Use tool

Image Converter

Convert between different image formats.

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help