Request Context (getContext)
Read incoming cookies, HTTP headers, normalized paths, and multi-runtime environment bindings—or set response cookies, headers, status codes, and redirects—synchronously anywhere in your server tree without prop drilling.
1. Overview & AsyncLocalStorage
In Dinou, every incoming HTTP request, RSC payload fetch, and Server Function call runs inside an isolated AsyncLocalStorage scope. Calling getContext() (exported identically from "dinou", "dinou/server", and route-contextual "./dinou") synchronously retrieves the active RequestContextStore for the current execution without passing req or res down through component props.
workerd), and Netlify Functions v2—including live KV/D1/R2 bindings via env.<Suspense> streams, PPR dynamic holes, and Server Components returned by Server Functions.1.1 Where getContext() Works
- Server Components (
page.tsx,layout.tsx,@slot/page.tsx, nested async RSCs, and<Suspense>holes). - Route Lifecycle Files (
getProps,validateParams,getCacheTags,getStaticPathsinpage_functions.tsandlayout_functions.ts). - Server Functions (
"use server"module-level and inline actions—including streamed JSX returned from an action). - Web Standards Plugins (
onRequest(request, context)indinou.config.tsreceives the same store as its second argument and also runs insideAsyncLocalStorage).
2. The RequestContextStore Shape
getContext() always returns a non-nullable RequestContextStore on the server (falling back to a safe server context with env populated if called outside an active HTTP request, such as in unit tests or build scripts):
| Property | Type | Description |
|---|---|---|
| req.cookies | Record<string, string> | Parsed incoming HTTP cookies for the current request. |
| req.headers | IncomingHttpHeaders | Lowercased incoming HTTP headers (e.g. authorization, accept-language, x-dinou-current-path). |
| req.query | Record<string, string | string[] | undefined> | Parsed URL query parameters (preserves multi-value arrays like ?tag=a&tag=b and empty values like ?flag=). |
| req.path | string | Normalized logical route pathname (e.g. "/dashboard" even during internal /____rsc_page____/dashboard SPA fetches). |
| req.rawPath | string | undefined | Raw wire HTTP pathname before RSC prefix normalization (e.g. "/____rsc_page____/dashboard"). |
| req.isRscRequest | boolean | undefined | true when serving an internal React Server Components wire fetch (/____rsc_*). |
| req.method | "GET" | "POST" | string | HTTP verb of the incoming request. |
| res | ResponseProxy | Methods to mutate the outgoing HTTP response: cookie(), clearCookie(), setHeader(), status(), redirect(). |
| env | DinouEnv | Zero-copy unified proxy across Cloudflare bindings (KV, D1, R2), Netlify.env, process.env, and Deno.env. |
| ctx | any | Platform execution context (e.g. Cloudflare/Netlify ctx.waitUntil(promise)). |
| [customKey] | any | Arbitrary request-scoped properties attached by plugin.onRequest (e.g. userId, locale, tenant). |
3. Reading Request Data (req)
Access cookies, HTTP headers, or request metadata directly inside any Server Component or page_functions.ts loader:
// src/account/page.tsx
import { getContext, redirect } from "dinou";
import { verifySession } from "@/lib/auth";
export default async function AccountPage() {
const { req } = getContext();
const token = req.cookies.session_id;
const userAgent = req.headers["user-agent"] ?? "unknown";
if (!token) {
return redirect("/login");
}
const user = await verifySession(token);
if (!user) {
return redirect("/login");
}
return (
<main>
<h1>Welcome, {user.name}</h1>
<p>Active route: {req.path}</p>
<p>Client: {userAgent}</p>
</main>
);
}// src/account/page_functions.ts
import { getContext, redirect } from "dinou";
import { verifySession } from "@/lib/auth";
export const revalidate = 0;
export async function getProps() {
const { req } = getContext();
const user = await verifySession(req.cookies.session_id);
if (!user) {
return redirect("/login");
}
return { user };
}Tip: Prefer Universal Hooks for Path & Query Strings
usePathname() and useSearchParams() — they work identically in both Server Components and Client Components and automatically re-render on client-side SPA transitions. Use getContext().req when you need cookies, HTTP headers, HTTP method, or server-only metadata.4. Mutating HTTP Responses (res)
getContext().res exposes a portable ResponseProxy that translates cleanly into native HTTP headers and Set-Cookie directives across Node.js, Bun, Deno, Cloudflare Workers, and Netlify:
// src/actions/auth.ts
"use server";
import { getContext } from "dinou";
export async function signIn(email: string, password: string) {
const { res, env } = getContext();
const token = await createSignedSession(email, password, env.AUTH_SECRET);
res.cookie("session_id", token, {
httpOnly: true,
secure: env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 24 * 7, // 7 days (in seconds)
});
return { ok: true };
}
export async function signOut() {
const { res } = getContext();
res.clearCookie("session_id", { path: "/" });
}// src/articles/[slug]/page.tsx
import { getContext } from "dinou";
import type { PageProps } from "./dinou";
export default async function ArticlePage({ params }: PageProps) {
const { res } = getContext();
const article = await fetchArticle(params.slug);
if (article?.archived) {
res.status(410); // HTTP 410 Gone
return <main><h1>This article has been archived.</h1></main>;
}
// Override outgoing CDN cache headers before streaming starts
res.setHeader("Cache-Control", "public, s-maxage=300, stale-while-revalidate=60");
return <article>{article?.body}</article>;
}Streaming Timing & Redirection
res (status, setHeader, cookie) must execute before HTTP headers are flushed (i.e., outside deferred <Suspense> streaming holes or inside onRequest / Server Functions). For page redirects in Server Components or getProps(), prefer return redirect("/login"), which handles HTTP 302, SPA x-rsc-redirect, and post-stream <ClientRedirect /> fallbacks automatically.5. SSG, PPR & Automatic Static Bailout Rules
Because Dinou is Static by Default, it wraps request-specific fields in an internal BailoutProxy during build-time SSG and on-demand ISG/PPR builds. Knowing which properties trigger dynamic execution lets you keep static shells fast without accidental de-optimizations:
| Context Access | Standard Route (ppr = false) | PPR Route (ppr = true) |
|---|---|---|
| req.cookies req.headers req.query | Triggers Automatic Static Bailout → route switches to Dynamic SSR. | Inside <Suspense>: registers a Dynamic PPR Hole (static shell stays cached). Outside <Suspense>: full-route bailout. |
| env req.path | 100% SSG-Safe → does not trigger dynamic bailout. | 100% Shell-Safe → baked into shell.html at build time. |
| Custom plugin fields (e.g. ctx.userId) | plugin.onRequest is skipped during build-time SSG (undefined at build time, populated on every runtime HTTP request). | Populated at request time inside dynamic PPR holes; always guard or provide a fallback if read in the static shell. |
See Static & Dynamic Rendering and 3D Layered Segmentation for full PPR and noDynamic() details.
6. Unified env, ctx & Custom Plugin State
getContext().env is a live zero-copy Proxy unifying Cloudflare Workers bindings (KV, D1, R2, secrets), Netlify.env, process.env (including .env* hot-reload in dinou dev), and Deno.env.get(). Meanwhile, any property assigned in a plugin's onRequest(request, context) hook flows automatically to Server Components, page_functions.ts, and Server Functions:
// src/plugins/tenant.ts
import type { DinouPlugin } from "dinou";
export function tenantPlugin(): DinouPlugin {
return {
name: "tenant-resolver",
async onRequest(request, context) {
const host = request.headers.get("host") ?? "localhost";
context.tenantId = host.split(".")[0];
// Schedule non-blocking background telemetry on Cloudflare / Netlify
context.ctx?.waitUntil?.(
logEdgeHit(context.req.path, context.env.ANALYTICS_TOKEN)
);
},
};
}// src/dashboard/page.tsx
import { getContext } from "dinou";
export default async function DashboardPage() {
const { tenantId, env } = getContext();
// Works across Node/Bun/Deno/Netlify (.env) AND Cloudflare Workers (KV/D1/secrets)
const cachedSummary = env.TENANT_KV
? await env.TENANT_KV.get(`summary:${tenantId}`)
: null;
return (
<main>
<h1>Tenant: {tenantId}</h1>
<p>{cachedSummary ?? "Live summary"}</p>
</main>
);
}6.1 TypeScript Module Augmentation (dinou-env.d.ts)
To get strict autocomplete and type checking for your Cloudflare bindings and custom plugin properties on getContext(), augment DinouEnv and RequestContextStore in your root dinou-env.d.ts:
// dinou-env.d.ts
/// <reference types="dinou/env" />
declare module "dinou" {
interface DinouEnv {
AUTH_SECRET: string;
ANALYTICS_TOKEN?: string;
TENANT_KV?: KVNamespace;
}
interface RequestContextStore {
tenantId?: string;
userId?: string | null;
}
}7. Server-Only Boundary & Passing Data to Client Components
getContext() is strictly server-only. If invoked inside a "use client" component running in the browser, Dinou logs a console error and returns a safe empty fallback (env: {}, empty cookies/headers, no-op res).
How to Pass Server Context Values to Client Components Safely
getProps() in page_functions.ts) using getContext(), and pass them explicitly as serializable props into your "use client" component. Never forward the entire env object or secret tokens to the browser. For build-time public client constants, use process.env.DINOU_PUBLIC_*.- Always set
httpOnly: trueandsameSite: "lax"on session cookies. - Verify JWT cookies cryptographically (never trust raw Base64 cookie claims).
- Never pass
getContext().envdirectly to a"use client"prop. - Keep
getContext()calls inside Server Components, loaders, plugins, or Server Functions.