{"id":12736,"library":"iron-session","title":"Iron Session","description":"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.","status":"active","version":"8.0.4","language":"javascript","source_language":"en","source_url":"https://github.com/vvo/iron-session","tags":["javascript","session","secure","stateless","cookie","encryption","security","next.js","node.js","typescript"],"install":[{"cmd":"npm install iron-session","lang":"bash","label":"npm"},{"cmd":"yarn add iron-session","lang":"bash","label":"yarn"},{"cmd":"pnpm add iron-session","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Since v6.0.0 (the TypeScript rewrite), iron-session primarily uses ESM for its main exports. CommonJS `require()` is not officially supported for the primary entry point.","wrong":"const getIronSession = require('iron-session');","symbol":"getIronSession","correct":"import { getIronSession } from 'iron-session';"},{"note":"This is a TypeScript type definition. Use `import type` to ensure it's removed during compilation, preventing potential runtime issues or bundle size increases.","wrong":"import { IronSession } from 'iron-session';","symbol":"IronSession","correct":"import type { IronSession } from 'iron-session';"},{"note":"Both `sealData` and `unsealData` are named exports for manual encryption/decryption of data outside the standard session flow.","wrong":"import sealData from 'iron-session';","symbol":"sealData","correct":"import { sealData } from 'iron-session';"}],"quickstart":{"code":"import { getIronSession, type IronSession } from 'iron-session';\nimport { type NextApiRequest, type NextApiResponse } from 'next'; // Example for Next.js\n\n// Define a type for your session data\ninterface SessionData {\n  username?: string;\n  isLoggedIn: boolean;\n  // Add other properties you want to store in the session\n}\n\n// Define session options, including a strong secret password\nconst sessionOptions = {\n  password: process.env.IRON_SESSION_PASSWORD ?? 'a-very-long-secret-password-at-least-32-chars-long',\n  cookieName: 'my-app-session-cookie',\n  cookieOptions: {\n    maxAge: 60 * 60 * 24 * 30, // 30 days\n    secure: process.env.NODE_ENV === 'production', // Set to true in production\n    httpOnly: true,\n    path: '/',\n    sameSite: 'lax'\n  }\n};\n\n// Example GET handler to retrieve session data\nexport async function getSessionHandler(req: NextApiRequest, res: NextApiResponse) {\n  const session = await getIronSession<SessionData>(req, res, sessionOptions);\n\n  // Initialize if not set for new sessions\n  if (session.isLoggedIn === undefined) {\n    session.isLoggedIn = false;\n  }\n\n  return res.status(200).json({ isLoggedIn: session.isLoggedIn, username: session.username });\n}\n\n// Example POST handler (e.g., login) to update session data\nexport async function loginHandler(req: NextApiRequest, res: NextApiResponse) {\n  const session = await getIronSession<SessionData>(req, res, sessionOptions);\n\n  // In a real app, you'd validate user credentials here\n  if (req.body.username === 'demo' && req.body.password === 'password') {\n    session.username = req.body.username;\n    session.isLoggedIn = true;\n    await session.save(); // Persist changes to the session cookie\n    return res.status(200).json({ message: 'Logged in successfully' });\n  }\n\n  return res.status(401).json({ message: 'Invalid credentials' });\n}\n\n// Example handler for logging out a user\nexport async function logoutHandler(req: NextApiRequest, res: NextApiResponse) {\n  const session = await getIronSession<SessionData>(req, res, sessionOptions);\n  session.destroy(); // This is synchronous since v8.0.1, removes the session cookie\n  await session.save(); // Ensure the cookie is cleared from the browser\n  return res.status(200).json({ message: 'Logged out successfully' });\n}","lang":"typescript","description":"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."},"warnings":[{"fix":"Migrate your code to use the `getIronSession(req, res, sessionOptions)` or `getIronSession(cookieStore, sessionOptions)` method directly. Refer to the official migration guide for specific examples.","message":"Version 8.0.0 significantly refactored the API to align with the Next.js App Router and simplify the overall surface. All previous opinionated wrapper functions like `withIronSessionSsr` or `withIronSessionApiRoute` have been removed in favor of a single `getIronSession()` method.","severity":"breaking","affected_versions":">=8.0.0"},{"fix":"If upgrading from `next-iron-session` (v5 or lower), a full migration is required. Install `iron-session` and update all imports and API calls according to the v6 migration guide. Ensure your project is configured for TypeScript if not already.","message":"Version 6.0.0 was a complete rewrite of the library in TypeScript and involved a package rename from `next-iron-session` to `iron-session`. This introduced numerous breaking changes to the API, types, and internal structure.","severity":"breaking","affected_versions":">=6.0.0"},{"fix":"Call `session.destroy()` without `await` or `.then()`. Remember to call `await session.save()` *after* `session.destroy()` to ensure the session cookie is correctly invalidated and cleared from the browser.","message":"As of v8.0.1, the `session.destroy()` method is synchronous and returns `void`. Previous versions might have returned a `Promise<void>`, leading to developers incorrectly awaiting or chaining `.then()` to it.","severity":"gotcha","affected_versions":">=8.0.1"},{"fix":"Always store your session password as an environment variable (e.g., `process.env.IRON_SESSION_PASSWORD`) and ensure it meets the minimum length and randomness requirements. Do not hardcode it in your source code.","message":"The `password` option in `sessionOptions` is critical for the security of your sessions. It must be a strong, cryptographically secure random string of at least 32 characters. Hardcoding this password or using a weak one makes your sessions vulnerable to decryption and tampering.","severity":"gotcha","affected_versions":">=6.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Update your import statements to use ES Module syntax: `import { getIronSession } from 'iron-session';`. Ensure your `package.json` specifies `\"type\": \"module\"` or use `.mjs` file extensions for your source files.","cause":"`iron-session` is primarily designed as an ES Module (ESM) since version 6.0.0. Using `require()` syntax in an ESM-only context will lead to this error.","error":"ReferenceError: require is not defined"},{"fix":"After calling `const session = await getIronSession(req, res, sessionOptions);`, access session properties directly on the `session` object. For type safety, define a `SessionData` interface and pass it to `getIronSession<SessionData>(...)`.","cause":"This TypeScript error often occurs when developers expect `req.session` to be automatically available on a Next.js request object without proper type augmentation or explicit session retrieval.","error":"Property 'session' does not exist on type 'NextApiRequest'"},{"fix":"Remove `await` or `.then()` from `session.destroy()`. Simply call `session.destroy();`. Remember to follow it with `await session.save()` if you want the cookie to be immediately cleared from the client.","cause":"This error arises when attempting to use `.then()` or `await` with `session.destroy()` after version 8.0.1, where `destroy()` was changed to be synchronous.","error":"TypeError: session.destroy(...).then is not a function"}],"ecosystem":"npm"}