Loading

Quipoin Menu

Learn • Practice • Grow

express-js / ExpressJS Sessions Management
tutorial

ExpressJS Sessions Management

Imagine you're shopping online. You add items to your cart, browse different pages, and the cart remembers what you added. How does the website know it's still you? This is where sessions come in. While cookies store data on the browser, sessions store data on the server and give the client a session ID (usually via a cookie) to identify them.

What are Sessions?

Sessions are a way to store user-specific data across multiple requests. Unlike cookies, session data is stored on the server, making it more secure for sensitive information. The server creates a unique session ID for each user and sends it to the browser via a cookie. On subsequent requests, the browser sends this ID, and the server looks up the session data.

Installing Express Session

Express doesn't have built-in session management. You need the express-session middleware:
npm install express-session

Setting Up Express Session
const express = require('express');
const session = require('express-session');
const app = express();

// Configure session middleware
app.use(session({
secret: 'your-secret-key', // Used to sign the session ID cookie
resave: false, // Don't save session if unmodified
saveUninitialized: false, // Don't create session until something stored
cookie: {
maxAge: 1000 * 60 * 60 * 24, // 1 day
httpOnly: true, // Prevent client-side JS access
secure: false // Set to true if using HTTPS
}
}));

Session Options Explained
  • secret Used to sign the session ID cookie (keep it secret!)
  • resave Forces session to be saved back to store even if unmodified
  • saveUninitialized Saves new but unmodified sessions
  • cookie Settings for the session cookie (maxAge, httpOnly, secure, sameSite)

Storing Data in Sessions

Session data is stored in req.session. You can add any properties you want:
app.get('/login', (req, res) => {
// Simulate login
req.session.user = {
id: 123,
username: 'john',
role: 'user'
};
req.session.visits = (req.session.visits || 0) + 1;
res.send('Logged in successfully');
});

Reading Session Data

Access session data from any route handler:
app.get('/dashboard', (req, res) => {
if (req.session.user) {
res.send(`
Welcome back, ${req.session.user.username}!
You've visited this page ${req.session.visits} times.
`);
} else {
res.send('Please login first');
}
});

Destroying Sessions (Logout)

To log out a user, destroy the session:
app.get('/logout', (req, res) => {
req.session.destroy((err) => {
if (err) {
console.error('Error destroying session:', err);
return res.status(500).send('Could not log out');
}
res.send('Logged out successfully');
});
});

// Alternatively, you can clear specific properties
app.get('/logout-simple', (req, res) => {
req.session.user = null;
res.send('Logged out');
});

Practical Example: Shopping Cart with Sessions
const express = require('express');
const session = require('express-session');
const app = express();

app.use(express.urlencoded({ extended: true }));
app.use(session({
secret: 'my-secret-key',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 30 * 60 * 1000 } // 30 minutes
}));

// View products
app.get('/products', (req, res) => {
const products = ['Laptop', 'Phone', 'Headphones', 'Mouse'];
let html = '

Products

    ';
    products.forEach((product, index) => {
    html += `
  • ${product} Add to Cart
  • `;
    });
    html += '
View Cart';
res.send(html);
});

// Add to cart
app.get('/add-to-cart/:productId', (req, res) => {
const productId = req.params.productId;
const products = ['Laptop', 'Phone', 'Headphones', 'Mouse'];
const productName = products[productId];

// Initialize cart if not exists
if (!req.session.cart) {
req.session.cart = [];
}

// Add product to cart
req.session.cart.push({
id: productId,
name: productName
});

res.redirect('/products');
});

// View cart
app.get('/cart', (req, res) => {
const cart = req.session.cart || [];
if (cart.length === 0) {
return res.send('Your cart is empty. Shop now');
}

let html = '

Your Cart

    ';
    cart.forEach((item, index) => {
    html += `
  • ${item.name} Remove
  • `;
    });
    html += '
Continue Shopping';
res.send(html);
});

// Remove from cart
app.get('/remove-from-cart/:itemIndex', (req, res) => {
const itemIndex = parseInt(req.params.itemIndex);
if (req.session.cart && req.session.cart[itemIndex]) {
req.session.cart.splice(itemIndex, 1);
}
res.redirect('/cart');
});

// Clear cart
app.get('/clear-cart', (req, res) => {
req.session.cart = [];
res.redirect('/cart');
});

Session Stores

By default, sessions are stored in memory. This is fine for development but not for production. In production, you should use a persistent store like Redis, MongoDB, or MySQL:
// Example with Redis
const RedisStore = require('connect-redis')(session);
const redisClient = require('redis').createClient();

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

Two Minute Drill
  • Sessions store user data on the server, identified by a session ID cookie.
  • Use express-session middleware for session management.
  • Session data is available in req.session.
  • Important options: secret, resave, saveUninitialized, cookie.
  • Destroy sessions with req.session.destroy() for logout.
  • Use persistent stores (Redis, MongoDB) for production.
  • Sessions are perfect for shopping carts, authentication, and user preferences.

Need more clarification?

Drop us an email at career@quipoinfotech.com