Cookie Utilities
A lightweight utility module for managing HTTP cookies in TezX applications. Includes functions for reading, parsing, setting, and deleting cookies in a consistent and type-safe way.
Import
import {
getCookie,
allCookies,
setCookie,
deleteCookie,
serializeOptions,
} from "tezx/cookie";API Reference
getCookie(ctx: Context, name: string): string | undefined
Returns the value of a specific cookie from the incoming request.
Parameters
ctx: Request contextname: Cookie name
Returns
- The cookie value, or
undefinedif not found
Example
const session = getCookie(ctx, "session_id");allCookies(ctx: Context): Record<string, string>
Parses and returns all cookies as a key-value object.
Parameters
ctx: Request context
Returns
- Object containing all parsed cookies
Example
const cookies = allCookies(ctx);setCookie(ctx: Context, name: string, value: string, options?: CookieOptions): void
Sets a cookie on the response.
Parameters
ctx: Response contextname: Cookie namevalue: Cookie valueoptions: Optional cookie attributes
Example
setCookie(ctx, "session_id", "abc123", {
maxAge: 3600,
httpOnly: true,
secure: true,
});deleteCookie(ctx: Context, name: string, options?: CookieOptions): void
Deletes a cookie by expiring it immediately.
Parameters
ctx: Response contextname: Cookie nameoptions: Must match original attributes (e.g.,path,domain)
Example
deleteCookie(ctx, "session_id", { path: "/" });serializeOptions(options: CookieOptions): string
Serializes cookie options into a Set-Cookie header string fragment.
Parameters
options: Cookie configuration
Returns
- A serialized string suitable for HTTP headers
Example
serializeOptions({ maxAge: 3600, httpOnly: true });CookieOptions Interface
| Property | Type | Description |
|---|---|---|
maxAge | number | Cookie lifetime in seconds |
expires | Date | Absolute expiration date |
path | string | Path where the cookie is valid |
domain | string | Domain where the cookie applies |
secure | boolean | Sends only over HTTPS |
httpOnly | boolean | Prevents JS access in the browser |
sameSite | 'Strict' | 'Lax' |
Best Practices
- Use
httpOnlyandsecurefor all sensitive cookies. - Set
sameSite: 'Strict'or'Lax'to reduce CSRF risks. - Always match the original
pathanddomainwhen deleting cookies. - Prefer
maxAgeoverexpiresfor predictable control.
Response
The TezX framework provides a rich response system via the ctx object. This system makes it easy to return JSON, HTML, text, files, redirects, and custom responses with a clean API.
getConnInfo
Retrieves detailed connection information of the client making the current request. This function is typically used in middleware for rate-limiting, bot detection, or logging purposes.