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/sessionnpm install @bklarjs/sessionBasic 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: "/",
}));| Option | Type | Default | Description |
|---|---|---|---|
store | SessionStore | MemoryStore | Storage backend |
cookieName | string | "sid" | Cookie name |
maxAge | number | 86400000 (24h) | Session TTL in ms |
httpOnly | boolean | true | Cookie httpOnly flag |
secure | boolean | false | Cookie secure flag |
sameSite | string | "Lax" | Cookie SameSite |
path | string | "/" | 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;
}
}