Cookies and Sessions

Cookies and sessions are essential components of web development, enabling applications to maintain state and persist user data across different requests. Understanding how to effectively use cookies and sessions in Express.js will allow you to create more interactive and secure web applications.

In this chapter, we’ll dive deep into the concepts of cookies and sessions, exploring their basics, how they work in Express.js, and advanced use cases. By the end, you’ll have a thorough understanding of how to manage user data and state across multiple requests.

Understanding Cookies

What are Cookies?

Cookies are small pieces of data stored on the client-side (in the user’s browser) that are sent with every HTTP request to the server. They are often used to remember user preferences, session data, or tracking information.

Cookies have the following characteristics:

  • Key-Value Pairs: Cookies are stored as key-value pairs.
  • Expiration: Cookies can have an expiration date after which they are automatically deleted.
  • Domain and Path: Cookies are associated with specific domains and paths, controlling where they are sent.

Setting and Reading Cookies in Express.js

In Express.js, setting and reading cookies is straightforward, thanks to the cookie-parser middleware.

Installing cookie-parser

First, install the cookie-parser middleware:

				
					npm install cookie-parser

				
			

Setting Up cookie-parser

To use cookies in your Express.js application, you need to set up cookie-parser as middleware.

Example 1: Setting Up cookie-parser

File: app.js

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

// Use cookie-parser middleware
app.use(cookieParser());

// Route to set a cookie
app.get('/set-cookie', (req, res) => {
  res.cookie('username', 'JohnDoe', { maxAge: 900000, httpOnly: true });
  res.send('Cookie has been set');
});

// Route to read a cookie
app.get('/get-cookie', (req, res) => {
  const username = req.cookies.username;
  res.send(`Cookie Value: ${username}`);
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

				
			

Explanation:

  • cookieParser(): This middleware enables reading cookies from the req.cookies object.
  • res.cookie(): Sets a cookie named username with the value JohnDoe. The cookie has a maximum age of 15 minutes and is marked as httpOnly, meaning it cannot be accessed via client-side JavaScript.
  • req.cookies: Accesses the cookies sent by the client.

Output:

  1. Navigating to /set-cookie sets the username cookie.
  2. Navigating to /get-cookie reads and displays the value of the username cookie
				
					Cookie Value: JohnDoe

				
			

Cookie Options and Security

Cookies come with various options that control their behavior, including security settings like httpOnly and secure.

Cookie Options

  • maxAge: The maximum age of the cookie in milliseconds.
  • expires: The exact expiration date of the cookie.
  • httpOnly: If true, the cookie is not accessible via JavaScript (document.cookie).
  • secure: If true, the cookie is only sent over HTTPS.
  • domain: The domain for which the cookie is valid.
  • path: The URL path that must exist in the request for the cookie to be sent.

Example 2: Using Cookie Options

File: app.js

				
					// Route to set a secure cookie
app.get('/set-secure-cookie', (req, res) => {
  res.cookie('sessionToken', 'abc123', {
    maxAge: 3600000, // 1 hour
    httpOnly: true,
    secure: true,
    sameSite: 'Strict',
  });
  res.send('Secure cookie has been set');
});

				
			

Explanation:

  • secure: true: Ensures the cookie is only sent over HTTPS connections.
  • sameSite: ‘Strict’: Prevents the browser from sending the cookie along with cross-site requests, mitigating cross-site request forgery (CSRF) attacks.

Deleting Cookies

Cookies can be deleted by setting their expiration date to a time in the past.

Example 3: Deleting a Cookie

File: app.js

				
					// Route to delete a cookie
app.get('/delete-cookie', (req, res) => {
  res.clearCookie('username');
  res.send('Cookie has been deleted');
});

				
			

Explanation:

  • res.clearCookie(‘username’): Deletes the username cookie by setting its expiration date to a time in the past.

Output:

Navigating to /delete-cookie deletes the username cookie, making it unavailable in future requests.

cookies

Understanding Sessions

What are Sessions?

Sessions are a server-side storage mechanism used to store user data across multiple HTTP requests. Unlike cookies, which store data on the client-side, sessions keep the data on the server and use a cookie (typically a session ID) to associate the session with the client.

Setting Up Sessions in Express.js

To manage sessions in Express.js, you can use the express-session middleware.

Installing express-session

First, install the express-session middleware:

				
					npm install express-session

				
			

Setting Up express-session

Example 4: Basic Session Setup

File: app.js

				
					const session = require('express-session');

// Use express-session middleware
app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: true,
  cookie: { maxAge: 60000 } // 1 minute
}));

// Route to set a session value
app.get('/set-session', (req, res) => {
  req.session.user = 'JohnDoe';
  res.send('Session has been set');
});

// Route to get the session value
app.get('/get-session', (req, res) => {
  const user = req.session.user;
  res.send(`Session Value: ${user}`);
});

				
			

Explanation:

  • express-session: Middleware to manage sessions in Express.js.
  • secret: A string used to sign the session ID cookie.
  • resave: Forces the session to be saved back to the session store, even if it wasn’t modified during the request.
  • saveUninitialized: Forces an uninitialized session to be saved to the store.
  • req.session: Used to store and retrieve session data.

Output:

  1. Navigating to /set-session sets the session value for user.
  2. Navigating to /get-session retrieves and displays the session value
				
					Session Value: JohnDoe

				
			

Configuring Session Options

express-session provides several options to customize session behavior:

  • cookie: Controls cookie settings, such as maxAge, httpOnly, secure, and sameSite.
  • store: Specifies the session store (e.g., a database) where sessions should be saved.
  • rolling: Forces a session identifier cookie to be set on every response. This resets the expiration date.

Example 5: Advanced Session Configuration

File: app.js

				
					app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: false,
  cookie: {
    maxAge: 60000, // 1 minute
    httpOnly: true,
    secure: false,
    sameSite: 'Strict'
  },
  rolling: true
}));

				
			

Explanation:

  • saveUninitialized: false: Ensures that an unmodified session is not saved to the store.
  • rolling: true: Resets the session cookie expiration on each request, keeping the session alive as long as the user is active.

Using a Session Store

By default, sessions are stored in memory, which is not suitable for production. Instead, you can use session stores like Redis, MongoDB, or a database to persist sessions.

Example 6: Using Redis as a Session Store

First, install the required packages:

				
					npm install connect-redis redis

				
			

File: app.js

				
					const RedisStore = require('connect-redis')(session);
const redis = require('redis');

// Create a Redis client
const redisClient = redis.createClient();

// Configure express-session to use Redis
app.use(session({
  store: new RedisStore({ client: redisClient }),
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: false,
  cookie: { maxAge: 60000 }
}));

				
			

Explanation:

  • RedisStore: A session store for express-session that uses Redis as the backend.
  • redis.createClient(): Creates a Redis client that connects to the Redis server.
  • store: Specifies that sessions should be stored in Redis.

Securing Sessions

Securing sessions is critical to protect user data and prevent session hijacking. Here are some best practices:

  • Use HTTPS: Always use secure connections (HTTPS) to prevent session data from being intercepted.
  • Set httpOnly Cookies: Prevent client-side access to the session cookie.
  • Regenerate Session IDs: Regenerate the session ID after authentication to prevent fixation attacks.

Example 7: Regenerating Session ID

File: app.js

				
					// Route to regenerate session ID after login
app.post('/login', (req, res) => {
  // Assuming authentication is successful
  req.session.regenerate((err) => {
    if (err) {
      return res.status(500).send('Error regenerating session');
    }
    req.session.user = 'JohnDoe';
    res.send('Logged in successfully');
  });
});

				
			

Explanation:

  • req.session.regenerate(): Creates a new session ID while retaining the session data, mitigating session fixation attacks.

Combining Cookies and Sessions

Using Cookies to Manage Sessions

In some cases, you may want to combine cookies and sessions, such as using a cookie to store a session token that identifies a session stored on the server.

Example 8: Cookie-Based Session Management

File: app.js

				
					// Route to set a session and cookie
app.get('/login', (req, res) => {
  const sessionToken = 'abc123';
  res.cookie('sessionToken', sessionToken, { maxAge: 3600000, httpOnly: true });
  req.session.token = sessionToken;
  res.send('Logged in and session started');
});

// Route to access session via cookie
app.get('/dashboard', (req, res) => {
  const sessionToken = req.cookies.sessionToken;
  if (sessionToken === req.session.token) {
    res.send('Welcome to your dashboard');
  } else {
    res.status(401).send('Unauthorized access');
  }
});

				
			

Explanation:

  • res.cookie(‘sessionToken’, sessionToken, { maxAge: 3600000, httpOnly: true }): Sets a secure, HTTP-only cookie with the session token.
  • req.cookies.sessionToken: Retrieves the session token from the cookie and compares it to the one stored in the session.

Output:

  1. Navigating to /login sets both a session and a session token cookie.
  2. Navigating to /dashboard checks if the session token in the cookie matches the session, granting access if they match.

In this chapter, we've covered the fundamentals of cookies and sessions in Express.js, including how to set, read, and manage them securely. Cookies and sessions are crucial for maintaining state in web applications, allowing you to track user activities and store important data across multiple requests.Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India