Responses & Errors

Cookie Management

Read, set, sign, and delete HTTP cookies using ctx.cookies. Configure global cookie defaults and cryptographically signed session cookies.

Taser.js includes a built-in cookie jar accessible via ctx.cookies. It handles cookie parsing, serializing, signing, and automatic Set-Cookie header accumulation on outgoing responses without requiring external cookie-parser middleware.


Reading Cookies

Use ctx.cookies.get() to read an incoming cookie by name, or ctx.cookies.getAll() to retrieve all cookies as a key-value record:

src/routes/me.get.ts
import { json } from "@taserjs/router/reply";
import { t } from "@taserjs/router";

export default t.get("/me").handler((ctx) => {
  // Read a single cookie:
  const theme = ctx.cookies.get("theme") ?? "light";

  // Read all cookies:
  const allCookies = ctx.cookies.getAll();

  return json({ theme, allCookies });
});

Setting Cookies

Use ctx.cookies.set() to set cookies. Taser.js automatically handles options and appends Set-Cookie headers to your response:

src/routes/preferences.post.ts
import { ok } from "@taserjs/router/reply";
import { z } from "zod";
import { t } from "@taserjs/router";

export default t
  .post("/preferences")
  .body(
    z.object({
      theme: z.enum(["light", "dark", "system"]),
    }),
  )
  .handler((ctx) => {
    ctx.cookies.set("theme", ctx.body.theme, {
      path: "/",
      maxAge: 60 * 60 * 24 * 365, // 1 year
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      sameSite: "Lax",
    });

    return ok({ success: true });
  });

Cryptographically Signed Cookies

Signed cookies prevent client-side tampering by attaching an HMAC signature to the cookie value.

1. Configure a Global Secret

Set your signing secret in src/taser.ts:

src/taser.ts
import { createTaserApp } from "@taserjs/router";
import { context } from "./context.js";

export default createTaserApp({
  cookies: {
    secret: process.env.COOKIE_SECRET || "your-secure-secret-key-32-chars-long",
    httpOnly: true,
    sameSite: "Lax",
    secure: process.env.NODE_ENV === "production",
  },
}).context(context);

2. Set and Verify Signed Cookies

src/routes/auth/login.post.ts
import { json, ok } from "@taserjs/router/reply";
import { z } from "zod";
import { t } from "@taserjs/router";

export default t
  .post("/auth/login")
  .body(
    z.object({
      userId: z.string(),
    }),
  )
  .handler(async (ctx) => {
    // Sets a cryptographically signed cookie:
    await ctx.cookies.setSigned("session_user", ctx.body.userId);

    return json({ message: "Logged in successfully" });
  });

Verify and read the signed cookie in protected endpoints:

src/routes/auth/session.get.ts
import { json, unauthorized } from "@taserjs/router/reply";
import { t } from "@taserjs/router";

export default t.get("/auth/session").handler(async (ctx) => {
  // Returns the verified string value, or false/undefined if signature is invalid or missing:
  const userId = await ctx.cookies.getSigned("session_user");

  if (!userId) {
    return unauthorized({ message: "Invalid or expired session cookie" });
  }

  const user = await ctx.db.getUser(userId);
  return json(user);
});

Deleting Cookies

Use ctx.cookies.delete() to clear a cookie by setting its maxAge to 0:

src/routes/auth/logout.post.ts
import { json } from "@taserjs/router/reply";
import { t } from "@taserjs/router";

export default t.post("/auth/logout").handler((ctx) => {
  // Deletes cookie and returns its prior value (if present):
  const previousSession = ctx.cookies.delete("session_user", { path: "/" });

  return json({ message: "Logged out", previousSession });
});

Taser.js natively supports browser cookie prefixes for enhanced transport security:

  • prefix: "secure": Prepends __Secure- to the cookie name and enforces secure: true.
  • prefix: "host": Prepends __Host- to the cookie name, enforces secure: true, path: "/", and prohibits the domain attribute.
// Sets a cookie named "__Host-session":
ctx.cookies.set("session", sessionId, {
  prefix: "host",
});

// Reads the "__Host-session" cookie:
const sessionId = ctx.cookies.get("session", "host");

Prop

Type


TaserCookieJar Methods Reference

Prop

Type