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

Next, you'll need to configure the 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.

// src/session/session.ts
import { getIronSession, IronSession, SessionOptions } from 'iron-session';
import * as http from 'http';

// Options used to configure Iron Session.
const sessionOptions: SessionOptions = {
  cookieName: 'session',
  password: '<your-generated-password>', // 32-character minimum
  cookieOptions: {
    httpOnly: true,
    maxAge: 1800, // The expiration time of the cookie in seconds.
    path: '/',
    sameSite: 'lax',
    secure: false, // IMPORTANT: This should only be set to false for development environments where HTTPS is not enabled on the server.
  },
};

// NextJS Page Router requires two session methods because it operates in two
// distinct server environments: middleware (Edge / web standard objects) and
// API routes/server-side rendering (Node.js native objects).

// Function used to retrieve the session from middleware.
export async function middlewareGetSession(req: Request, res: Response): Promise<IronSession> {
  return await getIronSession(req, res, sessionOptions);
}

// Function used to retrieve the session from API routes and server-side rendered pages.
export async function getSession(req: http.IncomingMessage, res: http.ServerResponse): Promise<IronSession> {
  return await getIronSession(req, res, sessionOptions);
}

// src/session/session.ts
import { getIronSession, IronSession, SessionOptions } from 'iron-session';
import { cookies } from 'next/headers';

const sessionOptions: SessionOptions = {
  cookieName: 'session',
  password: '<your-generated-password>', // 32-character minimum
  cookieOptions: {
    httpOnly: true,
    maxAge: 1800, // The expiration time of the cookie in seconds.
    path: '/',
    sameSite: 'lax',
    secure: false, // IMPORTANT: This should only be set to false for development environments where HTTPS is not enabled on the server.
  },
};

// NextJS App Router requires two session methods because it operates in two
// distinct server environments: middleware (Edge / web standard objects) and
// server components/route handlers using the Cookies API.

export async function middlewareGetSession(req: Request, res: Response): Promise<IronSession> {
  return await getIronSession(req, res, sessionOptions);
}

export async function getSession(): Promise<IronSession> {
  const cookieStore = await cookies();
  return await getIronSession(cookieStore, sessionOptions);
}

Now that Iron Session is configured, the getSession() and middlewareGetSession() functions can be used throughout your NextJS project to retrieve session information.


What’s Next

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