Express.js Session Handling

Session handling in Express.js is essential for maintaining user data between HTTP requests. Sessions enable storing user-specific data such as login credentials, preferences, and other session-specific details.

 

Key Features of Session Handling

  • State Management: Keeps user state across requests.
  • Secure Storage: Sensitive data can be stored securely using server-side methods.
  • Customizable: Easily integrates with different session stores like Redis or databases.
  • Simple API: Middleware like express-session simplifies session handling.

 

Setting Up Session Handling in Express.js

Install the express-session Middleware
This package is required to manage sessions.

npm install express-session

Basic Session Configuration
Add express-session middleware to your app.

Example:

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

app.use(session({
    secret: 'your_secret_key',
    resave: false, // Prevents resaving unchanged sessions
    saveUninitialized: true, // Saves uninitialized sessions
    cookie: { secure: false } // Set to true for HTTPS
}));

Storing and Retrieving Session Data
Use the req.session object to store and access session data.

Example:

app.get('/login', (req, res) => {
    req.session.user = { username: 'JohnDoe', role: 'admin' };
    res.send('User logged in');
});

app.get('/dashboard', (req, res) => {
    if (!req.session.user) return res.status(401).send('Access Denied');
    res.send(`Welcome ${req.session.user.username}`);
});

Destroying a Session
Use req.session.destroy() to log out a user or clear session data.

Example:

app.get('/logout', (req, res) => {
    req.session.destroy(err => {
        if (err) return res.status(500).send('Unable to log out');
        res.send('Logged out successfully');
    });
});

Using a Session Store
By default, sessions are stored in memory, which is not suitable for production. Use session stores like Redis for scalability.

Example with connect-redis:

npm install connect-redis redis
const RedisStore = require('connect-redis')(session);
const redis = require('redis');
const redisClient = redis.createClient();

app.use(session({
    store: new RedisStore({ client: redisClient }),
    secret: 'your_secret_key',
    resave: false,
    saveUninitialized: false
}));

 

Complete Example

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

const app = express();
const redisClient = redis.createClient();

app.use(session({
    store: new RedisStore({ client: redisClient }),
    secret: 'your_secret_key',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: false } // Set to true if using HTTPS
}));

// Login Route
app.post('/login', (req, res) => {
    req.session.user = { username: 'JohnDoe', role: 'admin' };
    res.send('Logged in successfully');
});

// Dashboard Route
app.get('/dashboard', (req, res) => {
    if (!req.session.user) return res.status(401).send('Access Denied');
    res.send(`Hello, ${req.session.user.username}`);
});

// Logout Route
app.get('/logout', (req, res) => {
    req.session.destroy(err => {
        if (err) return res.status(500).send('Error logging out');
        res.send('Logged out successfully');
    });
});

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

 

Summary

Session handling in Express.js simplifies user data management across multiple requests. Using the express-session middleware with or without external session stores enables scalable and secure session management for modern web applications.