Express.js Session Management

Session management lets your application remember users between requests by storing data on the server and identifying each user with a unique session ID. This capability becomes essential when you're building features like user login, access control, or personalized content. In Express.js, sessions are not built-in, but with the express-session middleware, you can easily manage sessions after a user logs in.



After successful authentication, you typically use sessions. Once the user provides valid credentials, you can store minimal identifying data in the session to maintain their login state. This technique allows users to stay logged in as they move across different pages without needing to authenticate on every request.

What Is Session Management?

Session management lets your server remember users between requests by assigning each user a unique session ID stored in a browser cookie. The server stores the actual data and uses the ID to retrieve it. This feature allows you to keep users logged in, save settings, and track activity securely.

Getting Started with express-session

Install the necessary packages:

npm install express express-session

Set up your Express app and session middleware:

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

app.use(express.urlencoded({ extended: true }));

app.use(session({
  secret: 'your_secret_key',          // Use a strong, unique secret
  resave: false,                      // Don't save unchanged sessions
  saveUninitialized: false,           // Don't store empty sessions
  cookie: { maxAge: 60000 }           // Session lasts 1 minute
}));

app.get('/', (req, res) => {
  res.send('Welcome! Session demo is working.');
});

Key Session Options

The express-session middleware supports several configuration options that control how sessions behave. Below are the most important ones you should understand when building secure and efficient applications.

Option Description
secret A required string used to sign the session ID cookie. Use a strong, unique key.
resave This action forces the session to be saved back to the store, even if no modifications were made. Set to false for better performance.
saveUninitialized Saves new sessions that are uninitialized. Set to false to avoid storing unnecessary sessions.
store Defines the session store (e.g., MongoDB, Redis). Use in production for persistence.
cookie.maxAge Time in milliseconds before the session cookie expires. It regulates the duration of the session.
cookie.secure Sends the cookie only over HTTPS. Set to true in production.
cookie.httpOnly Prevents JavaScript from accessing the cookie on the client side. Enhances security.
cookie.sameSite Controls how cookies are sent with cross-site requests. Use 'strict' or 'lax' to prevent CSRF.
name Sets the name of the session ID cookie. Defaults to 'connect.sid'. Can be customized.
rolling This action forces the session cookie to reset on every request, which extends its expiration. This feature proves to be beneficial for ongoing sessions.

Storing Session Data with Authentication

In a real-world application, session data should only be saved after a proper authentication process. The example below shows how to store session data securely after verifying user credentials.

// Sample user data (in a real app, retrieve from a database)
const users = [
  { username: 'johnDoe', password: 'password123' },
  { username: 'janeSmith', password: 'securePass' }
];

// Login route with basic authentication
app.post('/login', (req, res) => {
  const { username, password } = req.body;
  
  const user = users.find(user => user.username === username && user.password === password);
  
  if (user) {
    req.session.user = { username: user.username }; // Store minimal user data
    res.send(`Hello, ${user.username}. You have been logged in.`);
  } else {
    res.send('Invalid username or password.');
  }
});

// Protected dashboard route requiring authentication
app.get('/dashboard', (req, res) => {
  if (req.session.user && req.session.user.username) {
    res.send(`Welcome back, ${req.session.user.username}`);
  } else {
    res.send('Access denied. Please log in first.');
  }
});

In this example, the /login route authenticates the user. Session information is saved if the credentials match. The /dashboard route checks that session data exists before granting access.

Destroying a Session (Logout)

To log a user out, destroy the session and clear the cookie.

app.get('/logout', (req, res) => {
  if (req.session.user) {
    req.session.destroy(err => {
      if (err) return res.send('Error logging out');
      res.clearCookie('connect.sid');
      res.send('You have been logged out.');
    });
  } else {
    res.send('No active session found.');
  }
});

Conclusion

In this tutorial, you learned how to implement session management in Express.js using the express-session middleware. You saw how to configure session handling, store session data after user authentication, protect routes using session checks, and cleanly destroy sessions during logout. Session management is a critical feature in web applications that deal with user login and secure data handling.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram

Keep W3schools Growing with Your Support!
❤️ Support W3schools