Add Session Management

Implement session management so that a user's authenticated state persists across requests.

Now that you have implemented your authentication endpoints, we'll add the ability to manage user sessions. For more details on how session management works, please view our Session Management documentation.

💡

Do you need session management?

Short answer: Yes.

While session management is technically optional, it's very strongly recommended. Without session management, the user's authenticated state would be lost on each each request and they'd have to continually reauthenticate.


Install Session Library

For this guide, we'll use Iron Session to store session data within a cookie. Use your package manager CLI to install Iron Session into your project.

npm install iron-session
yarn add iron-session
pnpm add iron-session

Configure Session Middleware

Configure Iron Session middleware to enable encrypted, cookie-based sessions. As part of the configuration, you'll need to provide a password that is at least 32 characters long. To generate the password, you can use: https://1password.com/password-generator.

// app.ts
import { getIronSession } from 'iron-session';

...

// Initialize Iron Session middleware for cookie-based sessions.
app.use(async (req, res, next) => {
  req.session = await getIronSession(req, res, {
    cookieName: 'session',
    password: '<my-session-cookie-password>', // 32-character minimum
    cookieOptions: {
      httpOnly: true,
      maxAge: 1800, // The expiration time of the cookie in seconds.
      path: '/',
      sameSite: true,
      secure: false, // IMPORTANT: This should only be set to false for development environments where HTTPS is not enabled on the server.
    },
  });
  next();
});

...

Now that Iron Session is configured, the session for each authenticated user will be accessible on the req.session field throughout your Express routes and controllers.


What’s Next

Next, let's enhance the authentication routes you previously created to add session management logic.