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:
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:
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:
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
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:
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:
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 });
});Secure Cookie Prefixes (__Secure- and __Host-)
Taser.js natively supports browser cookie prefixes for enhanced transport security:
prefix: "secure": Prepends__Secure-to the cookie name and enforcessecure: true.prefix: "host": Prepends__Host-to the cookie name, enforcessecure: true,path: "/", and prohibits thedomainattribute.
// 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");Cookie Options Reference
Prop
Type
TaserCookieJar Methods Reference
Prop
Type
Related Guides
Reply Helpers
Send clean, status-discriminated HTTP responses using tree-shakeable reply helpers: json(), ok(), notFound(), and redirect().
Response Contracts
Enforce compile-time return shape safety and runtime response validation with .returns(). Eliminate response drift between backend and frontend.