session.ts

From the guide Supabase authentication in TypeScript: two safe ways, with code. Placeholder values only: put your own keys in environment variables, never in the code.

session.tsTypeScriptRawExternal
// session.ts: a signed session cookie. Server only.
// The cookie holds base64url(JSON payload) + "." + base64url(HMAC-SHA256 of that payload, keyed with SESSION_SECRET).
// Anyone can read the payload, nobody can change it without the secret, and it expires on its own.
import { createHmac, timingSafeEqual } from 'node:crypto';

// The __Host- prefix makes browsers refuse the cookie unless it is Secure, has Path=/ and has no Domain, so no other
// subdomain can set or replace it (MDN, Set-Cookie, read 2026-11-22).
export const SESSION_COOKIE = '__Host-session';
export const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days

export interface Session {
  userId: string;
  /** Unix time in milliseconds. */
  expiresAt: number;
}

// Read at call time, so tests can pass their own secret. A short secret is refused: it can be guessed offline.
const secretOf = (secret?: string): string => {
  const s = secret ?? process.env.SESSION_SECRET;
  if (!s) throw new Error('SESSION_SECRET is not set');
  if (Buffer.byteLength(s) < 32) throw new Error('SESSION_SECRET must be at least 32 bytes');
  return s;
};
const mac = (part: string, secret: string): Buffer => createHmac('sha256', secret).update(part).digest();

export function signSession(session: Session, secret?: string): string {
  const part = Buffer.from(JSON.stringify({ userId: session.userId, expiresAt: session.expiresAt })).toString('base64url');
  return `${part}.${mac(part, secretOf(secret)).toString('base64url')}`;
}

/** The session, or null for a bad format, a bad signature or an expired session. Never throws on bad input. */
export function verifySession(value: unknown, nowMs: number, secret?: string): Session | null {
  if (typeof value !== 'string') return null;
  const dot = value.indexOf('.');
  if (dot <= 0 || dot !== value.lastIndexOf('.')) return null;
  const part = value.slice(0, dot);
  const sig = value.slice(dot + 1);
  if (!/^[A-Za-z0-9_-]+$/.test(part) || !/^[A-Za-z0-9_-]+$/.test(sig)) return null;

  const given = Buffer.from(sig, 'base64url');
  const expected = mac(part, secretOf(secret));
  // timingSafeEqual throws on different lengths, so compare the lengths first (a length is not secret).
  if (given.length !== expected.length || !timingSafeEqual(given, expected)) return null;

  let parsed: unknown;
  try {
    parsed = JSON.parse(Buffer.from(part, 'base64url').toString('utf8'));
  } catch {
    return null;
  }
  if (typeof parsed !== 'object' || parsed === null) return null;
  const { userId, expiresAt } = parsed as Record<string, unknown>;
  if (typeof userId !== 'string' || userId === '') return null;
  if (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt) || expiresAt <= nowMs) return null;
  return { userId, expiresAt };
}

/** The Set-Cookie value: HttpOnly (no script can read it), Secure (HTTPS only), SameSite=Lax (not sent on cross-site POSTs). */
export function sessionCookie(value: string, session: Session, nowMs: number): string {
  const maxAge = Math.max(0, Math.floor((session.expiresAt - nowMs) / 1000));
  return `${SESSION_COOKIE}=${value}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${maxAge}`;
}

export function clearSessionCookie(): string {
  return `${SESSION_COOKIE}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0`;
}

/** One cookie from the request's Cookie header, or null. */
export function readCookie(request: Request, name: string): string | null {
  for (const part of (request.headers.get('cookie') ?? '').split(';')) {
    const [k, ...v] = part.trim().split('=');
    if (k !== name) continue;
    try {
      return decodeURIComponent(v.join('='));
    } catch {
      return null; // a malformed escape is not a cookie of ours
    }
  }
  return null;
}

Back to the guide