Iron Session

8.0.4 · active · verified Sun Apr 19

iron-session is a secure, stateless, and cookie-based session management library for JavaScript environments, primarily used in Node.js applications and Next.js projects (supporting both API Routes and the App Router). The current stable version is 8.0.4. It distinguishes itself by storing encrypted and signed session data directly within HTTP cookies, thereby eliminating the need for server-side storage or external databases, a pattern inspired by frameworks like Ruby On Rails. This design promotes statelessness, improving scalability and simplifying deployment strategies. While it doesn't adhere to a fixed release schedule, major versions typically introduce significant API adjustments or compatibility updates, such as the v8 release which focused on App Router support and API simplification. The library ships with comprehensive TypeScript types, ensuring a robust and type-safe development experience.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize, read, update, and destroy a user's session using `getIronSession` in a Next.js API Route context. It includes examples for handling user login/logout and managing session state, emphasizing proper type usage and secure password handling.

import { getIronSession, type IronSession } from 'iron-session';
import { type NextApiRequest, type NextApiResponse } from 'next'; // Example for Next.js

// Define a type for your session data
interface SessionData {
  username?: string;
  isLoggedIn: boolean;
  // Add other properties you want to store in the session
}

// Define session options, including a strong secret password
const sessionOptions = {
  password: process.env.IRON_SESSION_PASSWORD ?? 'a-very-long-secret-password-at-least-32-chars-long',
  cookieName: 'my-app-session-cookie',
  cookieOptions: {
    maxAge: 60 * 60 * 24 * 30, // 30 days
    secure: process.env.NODE_ENV === 'production', // Set to true in production
    httpOnly: true,
    path: '/',
    sameSite: 'lax'
  }
};

// Example GET handler to retrieve session data
export async function getSessionHandler(req: NextApiRequest, res: NextApiResponse) {
  const session = await getIronSession<SessionData>(req, res, sessionOptions);

  // Initialize if not set for new sessions
  if (session.isLoggedIn === undefined) {
    session.isLoggedIn = false;
  }

  return res.status(200).json({ isLoggedIn: session.isLoggedIn, username: session.username });
}

// Example POST handler (e.g., login) to update session data
export async function loginHandler(req: NextApiRequest, res: NextApiResponse) {
  const session = await getIronSession<SessionData>(req, res, sessionOptions);

  // In a real app, you'd validate user credentials here
  if (req.body.username === 'demo' && req.body.password === 'password') {
    session.username = req.body.username;
    session.isLoggedIn = true;
    await session.save(); // Persist changes to the session cookie
    return res.status(200).json({ message: 'Logged in successfully' });
  }

  return res.status(401).json({ message: 'Invalid credentials' });
}

// Example handler for logging out a user
export async function logoutHandler(req: NextApiRequest, res: NextApiResponse) {
  const session = await getIronSession<SessionData>(req, res, sessionOptions);
  session.destroy(); // This is synchronous since v8.0.1, removes the session cookie
  await session.save(); // Ensure the cookie is cleared from the browser
  return res.status(200).json({ message: 'Logged out successfully' });
}

view raw JSON →