iron-session

repository·main·Indexed 26 days ago

https://github.com/vvo/iron-session

A 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.

Tokens
2.2K
Snippets
10
Records
20
Agent score
88%

What's inside iron-session

  1. Configure Session Options

    main

    When 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: true
      • secure: true (set to false for local non-HTTPS development)
      • sameSite: "lax"
      • maxAge: (ttl === 0 ? 2147483647 : ttl) - 60
      • path: "/"
  2. Use iron-session in Next.js Server Components and Server Actions

    main

    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>;
    }
  3. Use iron-session in Next.js API Routes and Node.js/Express

    main

    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();
    }
  4. Use iron-session in Next.js App Router (Route Handlers)

    main

    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();
    }
  5. sealData(data, { password, ttl })

    main
    The underlying mechanism that powers 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.
  6. getIronSession<T>(cookieStore, sessionOptions)

    main

    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);
  7. getIronSession<T>(req, res, sessionOptions)

    main

    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);
  8. Configure SessionOptions

    main

    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 }.