Selected topic

Sessions

Session Management

Prefer practical output? Use related tools below while reading.

What is Session Management?

Session management is the process of storing and retrieving user-specific data between requests. In Express.js, sessions are used to keep track of user interactions across multiple requests.

Why do we need Sessions?

Sessions are necessary for applications that require user authentication, authorization, or storing temporary data. Without sessions, each request would be treated as a new, anonymous user.

Types of Session Management in Express:

  1. Express-Session: This is the most popular session management middleware for Express.js. It stores session data in memory by default but can also store it in a database, Redis, or other storage engines.
  2. Cookie-Session: This approach uses cookies to store session ID on the client-side and references to session data on the server.

Example using Express-Session:

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

const app = express();

// Create a session middleware with 30 minutes expiration time
app.use(session({
secret: 'secret-key',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 1800000 } // 30 minutes in milliseconds
}));

let count = 0;

// Get user ID from session or create a new one if it doesn't exist
app.get('/', (req, res) => {
const userId = req.session.userId;
if (!userId) {
req.session.userId = Math.floor(Math.random() * 100000);
} else {
count++;
console.log(User ${userId} has visited the page ${count} times);
}
res.send('Welcome to our website!');
});

// Clear session data on logout
app.get('/logout', (req, res) => {
req.session.destroy();
res.redirect('/');
});

In this example:

  • We create an Express.js app and add the express-session middleware.
  • We set up a secret key for the session cookie.
On each GET request to the root URL (/), we check if a user ID is stored in the session. If not, we generate a new one using Math.floor(Math.random() 100000). If it exists, we increment a counter and log a message to the console.
  • When the /logout endpoint is hit, we clear the session data by calling req.session.destroy().
Note that this example uses in-memory storage for sessions. In a production environment, you should store your session data securely using Redis or another storage engine.