Run the Next.js development server
mainTo start the development server for this Next.js example project, use the following command. Once running, you can view the application at http://localhost:3000.
pnpm devrepository·main·Indexed 26 days ago
https://github.com/vvo/iron-sessionA secure, stateless, and cookie-based session library for JavaScript (v8.0.4). It stores session data in signed and encrypted cookies, enabling server-side session management without a centralized session store. It provides integration for Node.js/Express and Next.js (API Routes, App Router, Server Components, and Server Actions) via the getIronSession function, and includes utility functions sealData and unsealData for encrypting and decrypting data.
To start the development server for this Next.js example project, use the following command. Once running, you can view the application at http://localhost:3000.
pnpm devInstall the iron-session package using pnpm:
pnpm add iron-sessionWhen calling getIronSession, you must provide a password and a cookieName.
password (required): A string at least 32 characters long used to encrypt the cookie. You can also provide an object with incrementing keys (e.g., {2: "...", 1: "..."}) to support password rotation; iron-session will use the highest numbered key for new cookies.cookieName (required): The name of the cookie to be stored.ttl (optional): Time-to-live in seconds. Defaults to 14 days. Setting this to 0 computes the maximum allowed value by cookies.cookieOptions (optional): Any option available from jshttp/cookie#serialize (except encode). Default settings include:httpOnly: truesecure: true (set to false for local non-HTTPS development)sameSite: "lax"maxAge: (ttl === 0 ? 2147483647 : ttl) - 60path: "/"In Next.js Server Components or Server Actions, use cookies() from next/headers to initialize the session.
// Next.js Server Components and Server Actions (App Router)
import { cookies } from 'next/headers';
import { getIronSession } from 'iron-session';
async function getIronSessionData() {
const session = await getIronSession(cookies(), { password: "...", cookieName: "..." });
return session
}
async function Profile() {
const session = await getIronSessionData();
return <div>{session.username}</div>;
}To manage sessions in traditional Node.js environments (like Express or Next.js API Routes), pass the req and res objects to getIronSession.
// Next.js API Routes and Node.js/Express.
import { getIronSession } from 'iron-session';
export async function get(req, res) {
const session = await getIronSession(req, res, { password: "...", cookieName: "..." });
return session;
}
export async function post(req, res) {
const session = await getIronSession(req, res, { password: "...", cookieName: "..." });
session.username = "Alison";
await session.save();
}For Next.js App Router Route Handlers, pass the cookies() function from next/headers to getIronSession.
// Next.js Route Handlers (App Router)
import { cookies } from 'next/headers';
import { getIronSession } from 'iron-session';
export async function GET() {
const session = await getIronSession(cookies(), { password: "...", cookieName: "..." });
return session;
}
export async function POST() {
const session = await getIronSession(cookies(), { password: "...", cookieName: "..." });
session.username = "Alison";
await session.save();
}sealData. It decodes a seal string back into its original data using the provided password and TTL.iron-session. It encrypts and signs any data into a seal string. This can be used for use cases like magic links where you need to pass secure, verifiable data through a URL.Retrieves an iron-session instance using a cookie store. This is used for Next.js App Router (Route Handlers, Server Components, and Server Actions) by passing cookies().
type SessionData = {
// Your data
}
const session = await getIronSession<SessionData>(cookies(), sessionOptions);Retrieves an iron-session instance using the request and response objects. This is used for Node.js/Express or Next.js API Routes.
type SessionData = {
// Your data
}
const session = await getIronSession<SessionData>(req, res, sessionOptions);When initializing a session, you must provide a SessionOptions object. This object defines how the session cookie is named, encrypted, and how long it lasts.
Key properties:
cookieName: A unique string used as the cookie name in the browser.password: A string or an object used for encryption. If using an object, it supports password rotation. Note: Passwords must be at least 32 characters long.ttl: The session validity time in seconds. Defaults to 1209600 (14 days). Setting ttl: 0 means no expiration.cookieOptions: Options passed to the underlying cookie library (e.g., httpOnly, secure, sameSite, path). To create a session cookie that expires when the browser closes, pass cookieOptions: { maxAge: undefined }.unsealData function is used to decrypt and verify data that was previously encrypted with sealData.