Security

Sessions

Session management middleware with pluggable stores.

Sessions

@bklarjs/session provides session management middleware. It stores session data on ctx.state.session, sets a signed cookie, and persists changes automatically.

Installation

bun add @bklarjs/session
npm install @bklarjs/session

Basic Usage

import { session } from "@bklarjs/session";

app.use(session());

app.get("/", (ctx) => {
  // Read session data
  const visits = (ctx.state.session?.visits || 0) + 1;

  // Write session data
  ctx.state.session!.visits = visits;

  return ctx.json({ visits, sid: ctx.state.sessionId });
});

The session ID is stored in a cookie (default: sid) and session data is persisted to a MemoryStore by default.

Configuration

app.use(session({
  cookieName: "myapp_sid",
  maxAge: 7 * 24 * 60 * 60 * 1000,  // 7 days
  httpOnly: true,
  secure: process.env.NODE_ENV === "production",
  sameSite: "Lax",
  path: "/",
}));
OptionTypeDefaultDescription
storeSessionStoreMemoryStoreStorage backend
cookieNamestring"sid"Cookie name
maxAgenumber86400000 (24h)Session TTL in ms
httpOnlybooleantrueCookie httpOnly flag
securebooleanfalseCookie secure flag
sameSitestring"Lax"Cookie SameSite
pathstring"/"Cookie path

MemoryStore

The default store keeps sessions in memory with automatic TTL-based cleanup every 60 seconds.

import { session, MemoryStore } from "@bklarjs/session";

const store = new MemoryStore();
app.use(session({ store }));

Custom Stores (Redis, SQLite)

Implement the SessionStore interface for any storage backend:

interface SessionStore {
  get(sid: string): SessionData | null | Promise<SessionData | null>;
  set(sid: string, data: SessionData, maxAge?: number): void | Promise<void>;
  destroy(sid: string): void | Promise<void>;
}

Type augmentation

Session types augment bklar's State interface. You can extend SessionData for typed session access:

declare module "@bklarjs/session" {
  interface SessionData {
    userId?: string;
    role?: string;
  }
}

On this page