📚 Complete API Reference
Explore all exports across dinou, dinou/server, and route lifecycle contracts (page_functions.ts & layout_functions.ts) with TypeScript signatures, runtime behavior, and practical usage patterns.
1. Components (dinou)Universal / Client
<Link>
"use client"Universal NavigationThe primary declarative navigation primitive in Dinou. Renders a semantic HTML <a> tag enhanced with client-side SPA soft navigation, automatic background prefetching on hover, relative filesystem path resolution, and optional cache bypassing.
Intercepts primary left-clicks to perform seamless client-side page transitions via push() without triggering full browser reloads. If modifier keys (Cmd, Ctrl, Shift, Alt), non-primary mouse buttons, target="_blank" (any target other than _self), download, or an external destination are used, it gracefully yields to native browser navigation.
By default, hovering over a link triggers an automatic background prefetch of the destination RSC payload and script chunks. When real-time accuracy is required, passing fresh= disables prefetching and forces an on-demand server roundtrip on click.
| Prop | Type | Default | Description |
|---|---|---|---|
| href | DinouLinkTarget | — | Primary destination URL. Strongly typed for compile-time route validation and Ctrl + Space IDE autocomplete across static routes (/dashboard), dynamic route patterns (/blog/[slug] with params), relative paths when paired with from (security, ./security, ../billing), query/hash suffixes, and external URLs. |
| to | DinouLinkTarget | — | Alias for href with identical type safety and autocomplete (evaluated as href || to). |
| params | Record<string, ...> | — | Conditionally required parameter dictionary whenever href or to contains dynamic [param] or [...param] placeholders (optional when all placeholders are [[optional]]). Values are interpolated and URL-encoded via encodeURIComponent. |
| from | DinouFromRoute | — | Source route pattern (e.g. "/dashboard/settings") anchoring relative navigation in href / to. Enables strict compile-time validation and autocomplete for bare ("security"), dot-slash ("./security"), and parent ("../billing") paths, and safely slices deeper browser pathnames when rendered inside a parent layout or @slot. Tip: Importing { Link } from route-contextual "./dinou" inside a route folder pre-binds from automatically so you can omit it! |
| prefetch | boolean | true | Whether to prefetch the destination RSC layout and page payloads on onMouseEnter. Automatically skipped when fresh={true}, targeting external URLs, same-page #hash anchors, download links, or non-_self targets (such as target="_blank"). |
| fresh | boolean | false | Forces an on-demand server roundtrip upon navigation, bypassing any client-side router cache. Automatically skips hover prefetching when set to true. |
| ...props | AnchorHTMLAttributes | — | All standard HTML anchor attributes (className, target, rel, style, aria-*, onClick). Custom onClick handlers execute first; calling e.preventDefault() prevents soft navigation. |
Filesystem Path Resolution
pathname:- Absolute (
/): Starts with a forward slash (e.g.,/dashboard). Resolves strictly from the application root domain. - Relative Child (
detailsor./details): Withfrom="/products", bothdetailsand./detailsautocomplete and resolve under that route directory to/products/details. - Relative Sibling / Parent (
../): Withfrom="/users/settings", navigating to../profileresolves up one directory level to/users/profile.
// src/components/nav-bar.tsx (Client Component)
"use client";
import { Link, usePathname } from "dinou";
export function NavigationBar() {
const pathname = usePathname();
const navItems = [
{ href: "/dashboard", label: "Dashboard" },
{ href: "/orders", label: "Orders" },
{ href: "/analytics", label: "Analytics" },
{ href: "/settings", label: "Settings" },
];
return (
<nav className="flex items-center gap-4 p-4 border-b">
{navItems.map((item) => {
const isActive = pathname === item.href || pathname.startsWith(`${item.href}/`);
return (
<Link
key={item.href}
href={item.href}
className={`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${
isActive
? "bg-primary text-primary-foreground"
: "text-muted-foreground hover:bg-muted hover:text-foreground"
}`}
>
{item.label}
</Link>
);
})}
</nav>
);
}// src/components/order-actions.tsx (Client Component)
"use client";
import { Link } from "dinou";
import { RefreshCw } from "lucide-react";
export function OrderQuickActions() {
return (
<div className="flex items-center gap-3">
{/* Normal soft navigation with hover prefetch */}
<Link
href="/orders/archive"
className="text-xs text-muted-foreground hover:underline"
>
View Archive
</Link>
{/* Forced server round-trip: bypasses client RSC cache */}
<Link
href="/orders/live"
fresh
prefetch={false}
className="inline-flex items-center gap-1.5 px-3 py-1 bg-emerald-600 text-white text-xs rounded hover:bg-emerald-700"
>
<RefreshCw className="h-3.5 w-3.5" />
<span>Live Monitor (Force Fresh)</span>
</Link>
</div>
);
}// src/dashboard/settings/page.tsx
"use client";
import { Link } from "./dinou"; // Route-contextual: pre-binds from="/dashboard/settings"
export default function SettingsSubNav({ postSlug }: { postSlug: string }) {
const handleAuditClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
// Custom logging or analytics before navigation
console.log("Navigating to security audit");
// Calling e.preventDefault() here cancels soft navigation
};
return (
<div className="flex flex-col gap-2">
{/* Contextual relative child ("security" or "./security"): resolves to /dashboard/settings/security */}
<Link
href="security"
onClick={handleAuditClick}
className="text-sm font-medium"
>
Security Settings
</Link>
{/* Contextual relative sibling: resolves to /dashboard/billing */}
<Link
href="../billing"
className="text-sm text-muted-foreground"
>
Billing & Subscriptions
</Link>
{/* Dynamic route pattern with compile-time required params interpolation */}
<Link
href="/blog/[slug]"
params={{ slug: postSlug }}
className="text-sm text-primary"
>
Read Release Notes
</Link>
{/* Internal link in a new tab or external link: gracefully yields to native browser navigation */}
<Link
href="/reports/latest.pdf"
target="_blank"
rel="noopener noreferrer"
className="text-xs text-blue-500 underline"
>
Open Report in New Tab
</Link>
</div>
);
}<ClientRedirect>
"use client"Declarative PrimitiveA declarative Client Component that triggers an immediate, seamless route replacement upon mounting in the browser. It renders no DOM markup (null) and executes a soft router replacement (replace: true), ensuring that the redirected URL does not create trap loops in the user's browser back history.
redirect()While redirect() is the imperative function typically used with early returns (e.g. return redirect("/login")), <ClientRedirect> is the underlying JSX component returned by redirect(). It enables you to express redirections declaratively directly inside your JSX element tree.
replace: true)When executed, <ClientRedirect> performs a router.replace() rather than a push(). This replaces the current entry in the browser's history stack so users clicking the browser Back button are not immediately bounced forward again in an infinite redirect loop.
| Prop | Type | Default | Description |
|---|---|---|---|
| to | string | Required | The destination path or URL to navigate to. Supports absolute internal paths (e.g. "/auth/sign-in"), relative paths (e.g. "./onboarding"), query parameters (e.g. "/pricing?plan=pro"), and external URLs (e.g. "https://checkout.stripe.com/...", which automatically delegate to window.location.replace()). |
// src/components/billing-gate.tsx (Client Component)
"use client";
import { ClientRedirect } from "dinou";
interface BillingGateProps {
hasActiveSubscription: boolean;
children: React.ReactNode;
}
export function BillingGate({ hasActiveSubscription, children }: BillingGateProps) {
// Declarative ternary redirection directly inside JSX
return hasActiveSubscription ? (
<>{children}</>
) : (
<ClientRedirect to="/pricing?upgrade=required" />
);
}// src/components/client-guard.tsx (Client Component)
"use client";
import { ClientRedirect } from "dinou";
import { useAuth } from "@/hooks/use-auth";
export function ClientAuthGuard({ children }: { children: React.ReactNode }) {
const { user, isLoading } = useAuth();
if (isLoading) {
return <div className="p-6 text-sm text-muted-foreground">Loading session...</div>;
}
if (!user) {
// Replaces browser history with /sign-in immediately upon mount
return <ClientRedirect to="/auth/sign-in?from=/dashboard" />;
}
return <>{children}</>;
}// Pattern A: Imperative function return (Universal: Server & Client)
import { redirect } from "dinou";
export default function PageA({ isAllowed }: { isAllowed: boolean }) {
if (!isAllowed) {
return redirect("/unauthorized");
}
return <div>Welcome to Page A</div>;
}
// Pattern B: Declarative JSX Component (Client Component)
import { ClientRedirect } from "dinou";
export function PageB({ isAllowed }: { isAllowed: boolean }) {
if (!isAllowed) {
return <ClientRedirect to="/unauthorized" />;
}
return <div>Welcome to Page B</div>;
}3. Type-Safe Routing (dinou)Zero-Runtime Type System
Dinou introduces zero-runtime type safety with auto-generated declaration files and seamless IDE autocompletion for routes and parameters.
PageProps<T, TProps>
TypeScript Genericpage.tsxOfficial TypeScript generic for typing React Page components (page.tsx). Accepts a route pattern string (constrained by DinouRoutePattern | DinouRegisteredSlotPattern) and an optional second type argument TProps for custom props returned by page_functions.ts (getProps), automatically inferring the strongly typed params object. Inside a route folder, importing PageProps from route-contextual "./dinou" pre-binds T automatically so only optional TProps is needed.
import type { PageProps } from "dinou";
// 1. Single dynamic route + custom props from page_functions.ts (getProps)
export default function BlogPost({
params,
title,
}: PageProps<"/blog/[slug]", { title: string }>) {
// ✅ params.slug is strongly typed as string
return <h1>{title} ({params.slug})</h1>;
}
// 2. Catch-all dynamic route
export function DocsPage({ params }: PageProps<"/docs/[...slug]">) {
// ✅ params.slug is strongly typed as string[]
return <h1>Document: {params.slug.join("/")}</h1>;
}
// 3. Zero-boilerplate alternative inside src/blog/[slug]/page.tsx
// import type { PageProps } from "./dinou";
// export default function Page({ params }: PageProps) { ... }LayoutProps<T, TProps>
TypeScript Genericlayout.tsxOfficial TypeScript generic for typing React Layout components (layout.tsx), constrained by DinouLayoutPattern (including intermediate horizontal layouts without a sibling page.tsx). Automatically types children: ReactNode, cumulative segment params: LayoutParams<T>, auto-inferred sibling parallel @slot props (via LayoutSlots<T>), and optional custom props TProps from layout_functions.ts (getProps).
import type { LayoutProps } from "dinou";
// Includes children, params.org, auto-inferred @sidebar slot, and custom layout_functions props
export default function WorkspaceLayout({
children,
params,
sidebar,
orgName,
}: LayoutProps<"/workspace/[org]", { orgName: string }>) {
return (
<section>
<header>{orgName} ({params.org})</header>
<div className="flex">
<aside>{sidebar}</aside>
<main>{children}</main>
</div>
</section>
);
}SlotProps<T> & NotFoundProps<T, TProps>
TypeScript Generics@slot/page.tsx & not_found.tsxDedicated generics for parallel route slots (SlotProps<T>, constrained by DinouSlotPattern) and 404 boundaries (NotFoundProps<T, TProps>, constrained by DinouNotFoundPattern, supporting root, leaf, and intermediate not_found.tsx files plus optional custom TProps from a sibling page_functions.ts).
import type { SlotProps, NotFoundProps } from "dinou";
// 1. Parallel @slot page (src/workspace/[org]/@analytics/page.tsx)
export function AnalyticsSlot({ params }: SlotProps<"/workspace/[org]/@analytics">) {
return <aside>Analytics for {params.org}</aside>;
}
// 2. Scoped 404 boundary (src/workspace/[org]/not_found.tsx)
export default function WorkspaceNotFound({
params,
}: NotFoundProps<"/workspace/[org]">) {
return <h1>Resource not found inside {params.org}</h1>;
}ErrorProps<T>
TypeScript Genericerror.tsxOfficial TypeScript interface for typing React Error Boundary components (error.tsx), constrained by DinouErrorPattern (covering page routes, intermediate folders, and parallel @slot/error.tsx boundaries). In addition to cumulative inferred params: ErrorParams<T>, it strictly types the caught error: Error.
import type { ErrorProps } from "dinou";
export default function DashboardError({ error, params }: ErrorProps<"/dashboard/[teamId]">) {
return (
<div>
<h2>Failed to load team {params.teamId}</h2>
<p>{error.message}</p>
</div>
);
}PageFunctions<TParams, TProps> & LayoutFunctions<TParams, TProps>
TypeScript GenericsServer Lifecycle ContractsCanonical TypeScript generics for typing server lifecycle files (page_functions.ts and layout_functions.ts). Exported from dinou, re-exported from dinou/server, and pre-bound automatically when imported from route-contextual "./dinou". PageFunctions accepts a DinouRoutePattern (or params dictionary), while LayoutFunctions accepts a DinouLayoutPattern (including intermediate layouts without a sibling page.tsx), providing full compile-time typing for getProps, getStaticPaths, validateParams, getCacheTags, revalidate, ppr, and allowISG.
import type { PageFunctions, LayoutFunctions } from "dinou";
// 1. Direct route string pattern (infers params & getStaticPaths shapes automatically)
export const getProps: PageFunctions<
"/blog/[slug]",
{ postTitle: string }
>["getProps"] = async (params) => {
return { postTitle: `Article: ${params?.slug}` };
};
// 2. Strict index-access typing for layout_functions.ts (including intermediate layouts)
export const ppr: LayoutFunctions<"/workspace/[org]">["ppr"] = true;
export const revalidate: LayoutFunctions["revalidate"] = 3600;
// 3. Zero-boilerplate alternative inside src/blog/[slug]/page_functions.ts
// import type { PageFunctions } from "./dinou";
// export const getStaticPaths: PageFunctions["getStaticPaths"] = ["hello-world"];RouteParams<T>
TypeScript UtilityParams InferenceA standalone utility type representing the runtime-resolved parameters dictionary of any registered segment pattern (constrained by DinouSegmentPattern: pages, layouts, parallel @slots, and error boundaries). Companion helpers LayoutParams<T>, SlotParams<T>, and ErrorParams<T> target those specific segment families. Ideal for typing Server Functions, services, or helper functions outside framework components.
| Pattern Segment | Route Example | Runtime RouteParams<T> | Navigation / getStaticPaths Input |
|---|---|---|---|
| [id] | /products/[id] | { id: string } | { id: string | number } |
| [...slug] | /docs/[...slug] | { slug: string[] } | { slug: (string | number)[] } |
| [[...slug]] | /shop/[[...slug]] | { slug: string[] } ([] on root) | { slug?: (string | number)[] } |
| [[tab]] | /settings/[[tab]] | { tab?: string } | { tab?: string | number } |
import type { RouteParams } from "dinou";
// 1. Single dynamic parameter
export async function getAuthorBio(params: RouteParams<"/blog/[slug]">) {
return fetchBioBySlug(params.slug); // params.slug is string
}
// 2. Catch-all dynamic parameter
export async function getDocsContent(params: RouteParams<"/docs/[...slug]">) {
return fetchDocsByPath(params.slug.join("/")); // params.slug is string[]
}
// 3. In custom helper types (note: for error.tsx, prefer native ErrorProps<T>)
interface CustomErrorWrapper {
error: Error;
params: RouteParams<"/blog/[slug]">;
}DinouRoute, DinouLinkTarget & DinouFromRoute
Union TypesOutward NavigationThe outward navigation type family generated into .dinou/types/routes.d.ts:
DinouRoute: Concrete navigable URLs (static routes, interpolated dynamic routes, query suffixes?key=val, hashes#section, and external schemeshttp://,https://,mailto:,tel:). Ideal for custom wrapper props such as<NavButton href={href} />.DinouLinkTarget: Union ofDinouRouteplus dynamic route patterns ("/blog/[slug]", with optional?/#suffix) so<Link>androuter.push()autocomplete dynamic routes and enforce a typedparamsobject whenever a[param]pattern is chosen.DinouFromRoute&DinouRelativeLinkTarget<TFrom>: Strictly validate relative paths ("sub","./sub","../sibling") against an explicitfromorigin (or automatically viaDinouScopedLinkTarget<TFrom>when importingLink/useRouterfrom contextual"./dinou").
import type { DinouRoute, DinouLinkTarget, DinouFromRoute } from "dinou";
import { Link, useRouter } from "dinou";
// 1. Typing custom navigation components accepting concrete URLs
interface NavButtonProps {
href: DinouRoute;
label: string;
}
export function NavButton({ href, label }: NavButtonProps) {
return <Link href={href}>{label}</Link>;
}
// 2. Programmatic navigation (concrete URL, pattern + params, or strict relative with from)
export function ActionPanel() {
const router = useRouter();
const goDocs = (destination: DinouRoute) => router.push(destination);
const goPost = (slug: string) =>
router.push("/blog/[slug]", { params: { slug } });
const goSibling = (from: DinouFromRoute = "/dashboard/settings") =>
router.push("../billing", { from });
return <button onClick={() => goDocs("/docs/api-reference")}>API</button>;
}DinouRoutePattern & Segment Pattern Unions
Union TypesInward DefinitionDinouRoutePattern represents all registered page route patterns across your application (e.g. "/blog/[slug]", "/docs/[...slug]") and constrains PageProps<T> and PageFunctions<T>. Companion segment unions enable dedicated Ctrl + Space autocomplete across every boundary type while complying with TypeScript declaration emit rules (TS4058):
DinouLayoutPattern— constrainsLayoutProps<T>,LayoutParams<T>, andLayoutFunctions<T>(includes intermediate layouts with no siblingpage.tsx).DinouSlotPattern— constrainsSlotProps<T>andSlotParams<T>(parallel@slotfolders, e.g."/dashboard/[org]/@analytics").DinouErrorPattern— constrainsErrorProps<T>andErrorParams<T>(pages, intermediate folders, and@slot/error.tsx).DinouNotFoundPattern— constrainsNotFoundProps<T>(root, leaf, and intermediatenot_found.tsxboundaries, excluding@slotfolders).DinouSegmentPattern— combined union of all page, layout, slot, and error patterns accepted byRouteParams<T>.
import type { DinouRoutePattern, PageProps } from "dinou";
// 1. Creating strongly typed page helper wrappers or metadata generators
export function definePageMeta<T extends DinouRoutePattern>(
route: T,
generator: (props: PageProps<T>) => { title: string; description?: string }
) {
return generator;
}
// ✅ Valid: autocompletes route patterns and infers correct params
export const postMeta = definePageMeta("/blog/[slug]", ({ params }) => {
return { title: `Reading: ${params.slug}` };
});
// ❌ TypeScript error if using an unregistered route pattern
// definePageMeta("/invalid/route/[id]", ...);Contextual "./dinou" Module
Zero Boilerplate.dinou/routes/**/dinou.{js,d.ts}Every active route directory under src/ receives an auto-generated virtual module at .dinou/routes/<dir>/dinou.{js,d.ts} (kept up to date by dinou dev, dinou build, and dinou typegen, wired via TypeScript rootDirs: ["src", ".dinou/routes"]). Importing from "./dinou" pre-binds ROUTE, PageProps, LayoutProps, SlotProps, ErrorProps, NotFoundProps, PageFunctions, LayoutFunctions, RouteParams, Link, and memoized useRouter to that folder—while re-exporting all root dinou runtime APIs and types (including DinouEnv).
// src/workspace/[org]/settings/page.tsx
import { Link, ROUTE, type PageProps } from "./dinou";
export default function SettingsPage({ params }: PageProps) {
// ✅ params.org is inferred automatically without writing PageProps<"/workspace/[org]/settings">
// ✅ ROUTE === "/workspace/[org]/settings"
return (
<main>
<h1>Settings for {params.org}</h1>
{/* Relative targets autocomplete & validate without passing from="..." */}
<Link href="security">Security</Link>
<Link href="../members">Team Members</Link>
</main>
);
}4. Server Context & Config (dinou)Server-Side Execution
getContext()
Server-Only PrimitiveReturns: RequestContextStoreSynchronously accesses the active HTTP request, response proxy, and unified server environment via AsyncLocalStorage (exported from both "dinou" and "dinou/server"). In Dinou, getContext() operates across Server Components (RSC), Server Functions ("use server"), plugin.onRequest, and route segment contracts in page_functions.ts and layout_functions.ts without prop drilling. Outside an active HTTP request on the server, it returns a safe fallback RequestContextStore with env populated via createUnifiedEnv().
Request & Response Store Reference
Overview of the read-only request metadata (ctx.req) and server response mutation proxies (ctx.res).
ctx.req)Record<string, string | string[]>).Record<string, string>).IncomingHttpHeaders)."/dashboard", normalized even on internal /____rsc_* SPA wire fetches)."/____rsc_page____/dashboard") and boolean flag indicating whether the current request is an internal RSC SPA wire fetch."GET", "POST").DinouEnv): merges text env vars (process.env, Deno.env, Netlify env) with live Edge bindings (Cloudflare D1, KV, R2, Durable Objects).ctx.waitUntil()).ctx.res)httpOnly, secure, sameSite, maxAge, expires, and path.200, 201, 404).302).Any custom data attached to context inside a plugin's onRequest(request, context) hook (such as context.user, context.session, or context.tenant) is preserved across the entire request lifecycle and can be read synchronously via getContext() in any Server Component or Server Function.
DinouEnv):Accessible directly at the root of getContext() across Node.js, Bun, Deno, Cloudflare Workers, Netlify, and SSG. Augment interface DinouEnv in a .d.ts file to get full TypeScript autocompletion for KV, D1, R2 bindings, and secrets.
Reading ctx.req.cookies, ctx.req.headers, or ctx.req.query—or calling ctx.res.*—inside a Server Component automatically triggers Automatic Static Bailout (or registers a Dynamic PPR Hole inside <Suspense> when ppr = true). HTTP headers, status codes, and httpOnly cookies can only be emitted before streaming starts; inside deferred <Suspense> blocks, use return redirect("/path").
Never invoke getContext() directly inside a Client Component running in the browser. In browser environments, Dinou logs an error and returns an empty fallback object with no-op response methods. Always read confidential cookies, secrets, or database records on the server and pass only sanitized props to Client Components.
Production Implementation Patterns
Explore real-world patterns for Server Components, Server Functions, route segment lifecycle hooks, and plugin state retrieval.
// src/profile/page.tsx (Server Component)
import { getContext, redirect } from "dinou";
import { db } from "@/lib/db";
export default async function ProfilePage() {
const ctx = getContext();
// Read authenticated session cookie securely on the server
// (reading cookies triggers Automatic Static Bailout on static routes)
const sessionToken = ctx.req.cookies.auth_session;
if (!sessionToken) {
return redirect("/login?from=/profile");
}
// Extract client IP and user agent for security logging
const clientIp = ctx.req.headers["x-forwarded-for"] || "127.0.0.1";
const userAgent = ctx.req.headers["user-agent"] || "unknown";
const user = await db.users.findByToken(sessionToken);
return (
<div className="p-6">
<h1 className="text-2xl font-bold">Welcome, {user.name}</h1>
<p className="text-sm text-muted-foreground">
Session active from IP: {clientIp} ({userAgent})
</p>
</div>
);
}// src/actions/preferences.ts
"use server";
import { getContext } from "dinou";
export async function updateThemePreference(theme: "light" | "dark" | "system") {
const ctx = getContext();
// Mutate an outgoing HTTP response cookie from the Server Function
ctx.res.cookie("preferred_theme", theme, {
path: "/",
maxAge: 60 * 60 * 24 * 365, // 1 year
sameSite: "lax",
secure: process.env.NODE_ENV === "production",
});
return { success: true, theme };
}// src/dashboard/page_functions.ts
import { getContext, redirect } from "dinou";
// Evaluated before any JSX component rendering begins
export async function getProps() {
const ctx = getContext();
const tenantSlug = ctx.req.query.tenant as string | undefined;
if (!tenantSlug) {
return redirect("/onboarding");
}
// Read unified server secrets or Edge bindings (KV, D1, R2) via ctx.env
const apiSecret = ctx.env.TENANT_API_KEY;
return {
tenantSlug,
hasApiKey: Boolean(apiSecret),
logicalPath: ctx.req.path, // Always "/dashboard" even on SPA RSC fetches
};
}// 1. Plugin attaches authenticated user to context (dinou.config.ts)
import type { DinouPlugin } from "dinou";
export const authPlugin: DinouPlugin = {
name: "auth-guard",
async onRequest(request, context) {
const token = request.headers.get("Authorization");
if (token) {
// Injected directly into the request context store
context.user = await verifySession(token);
}
},
};
// 2. Server Component retrieves plugin state with zero prop-drilling
// src/dashboard/page.tsx (Server Component)
import { getContext } from "dinou";
export default async function DashboardPage() {
const ctx = getContext();
// Directly access custom plugin properties from the store
const currentUser = ctx.user;
return (
<div>
<h1>Welcome back, {currentUser?.name || "Guest"}</h1>
<p>Role: {currentUser?.role || "anonymous"}</p>
</div>
);
}defineConfig()
Configuration HelperRoot ConfigurationType-safe configuration helper providing autocomplete, IntelliSense, and schema validation for your application's root configuration file. Dinou discovers configuration files in deterministic precedence order: dinou.config.ts → dinou.config.mjs → dinou.config.js → dinou.config.cjs, compiles them ahead-of-time across Node.js, Bun, Deno, Cloudflare Workers, and Netlify (supporting TypeScript and @/* path aliases), and live hot-reloads changes in dinou dev. You can import defineConfig from "dinou" or the lightweight "dinou/config" subpath.
Configuration Schema Reference
All options defined on the DinouConfig interface accepted by defineConfig().
| Option | Type | Default | Description |
|---|---|---|---|
| reactCompiler | boolean | true | Enables or disables the React Compiler (babel-plugin-react-compiler) during production builds across Esbuild, Rollup, and Webpack. Individual components or hooks can also opt out locally using the "use no memo" directive. |
| reactStrictMode | boolean | true | Enables React 19 StrictMode double-rendering in development mode. Helps detect unexpected side effects and ensures strict concurrent rendering compatibility with React Compiler. |
| ppr | boolean | false | Global default for Partial Prerendering. When enabled, static-eligible routes pre-render an instant static HTML shell while streaming dynamic <Suspense> holes. Can be configured per layout branch in layout_functions.ts or overridden per route in page_functions.ts. |
| allowISG | boolean | true | Global default controlling whether dynamic route segments may generate and cache un-prerendered paths on demand via Incremental Static Generation (ISG). Set to false to restrict dynamic routes strictly to paths returned by getStaticPaths unless overridden per route or layout. |
| storage | StorageAdapter | Runtime default | Configures the storage backend for ISR/ISG HTML pages, RSC flight payloads, and DinouCacheSlot records. Defaults to FileSystemStorage on Node.js/Bun/Deno filesystem runtimes (DenoKVStorage on Deno Edge), MemoryStorage({ hydrateFromDisk: true }) on Netlify Functions, and CloudflareKVStorage(env.DINOU_CACHE) (or MemoryStorage) on Cloudflare Workers. Accepts built-in adapters (such as RedisStorage) or custom StorageAdapter implementations. |
| setupFiles | string[] | undefined | Array of setup or polyfill file paths injected at Line 1 across all bundler engines before any application modules load. Executed in deduplicated [...pluginSetupFiles, ...userSetupFiles] order. Supports relative paths, extensionless paths, tsconfig.json/jsconfig.json aliases (@/*), and npm package subpaths. When explicitly provided (including setupFiles: []), overrides the root dinou.setup.(mjs|js|ts) auto-discovery convention. |
| assetExtensions | string[] | [] | Additional file extensions (with or without leading dot, e.g. ["glb", "hdr", "wasm", "pdf"]) beyond Dinou's 26 built-in media/font formats recognized as static binary imports across Server Components, Client Components, and CSS url(...). Automatically content-hashed into /assets/[name]-[hash].[ext] across Esbuild, Rollup, and Webpack with ambient declare module "*.<ext>" declarations emitted in .dinou/types/routes.d.ts. |
| plugins | DinouPlugin[] | [] | Array of universal plugins providing onRequest Web Standards middleware, configureServer Node/Bun server hooks, and setupFiles injection. |
Production Configuration Patterns
Complete production configuration files for TypeScript and ES Modules projects.
// dinou.config.ts
import { defineConfig, type DinouPlugin } from "dinou/config";
const apiAuthPlugin: DinouPlugin = {
name: "api-guard",
async onRequest(request, context) {
// context.req.path is normalized even on /____rsc_* SPA fetches
if (context.req.path.startsWith("/api/protected")) {
const apiKey = request.headers.get("x-api-key");
if (!apiKey || apiKey !== context.env.INTERNAL_API_KEY) {
return Response.json(
{ error: "Unauthorized access: invalid or missing API key" },
{ status: 401 }
);
}
}
},
};
export default defineConfig({
reactCompiler: true,
reactStrictMode: true,
ppr: true,
allowISG: true,
assetExtensions: ["glb", "hdr", "wasm"],
setupFiles: ["@/setup/polyfills"],
plugins: [apiAuthPlugin],
});// dinou.config.js
import { defineConfig } from "dinou";
import { RedisStorage } from "dinou/server";
import Redis from "ioredis";
export default defineConfig({
// React Compiler & React 19 StrictMode defaults
reactCompiler: true,
reactStrictMode: true,
// Global Partial Prerendering & Dynamic ISG defaults
ppr: false,
allowISG: true,
// Distributed multi-region ISR cache storage
storage: new RedisStorage(
new Redis(process.env.REDIS_URL, {
maxRetriesPerRequest: 3,
enableReadyCheck: true,
})
),
// Universal Web Standards request plugins
plugins: [
{
name: "security-headers",
async onRequest(request) {
// Enforce HTTPS in production environments
const proto = request.headers.get("x-forwarded-proto");
if (process.env.NODE_ENV === "production" && proto === "http") {
const httpsUrl = request.url.replace("http://", "https://");
return Response.redirect(httpsUrl, 301);
}
},
},
],
});DinouPlugin
Web Standards MiddlewareEdge & Node.js CompatiblePlugins execute sequentially on the server entrypoint for every incoming HTTP request before route matching, cache lookups, or React rendering begins. Built on standard Web Request and Response primitives, plugins provide unified middleware capabilities across Node.js, Bun, Deno, Cloudflare Workers, and Netlify Functions (plus low-level Node/Bun server access via configureServer).
| Property | Type | Required | Description |
|---|---|---|---|
| name | string | Optional | Descriptive plugin identifier used for telemetry, developer diagnostics, and per-plugin error reporting in logs. |
| setupFiles | string[] | Optional | Array of setup or polyfill file paths injected at Line 1 across all bundler engines before user setupFiles and application modules load. Supports relative paths, @/* aliases, and npm package subpaths. |
| configureServer | (context: ServerHookContext) => void | Promise<void> | Optional | Low-level HTTP/HTTPS server hook invoked before server.listen() in Node.js and Bun (both dinou dev and production). Receives { server, isDev, use } to attach WebSockets (Socket.IO, ws), listeners, or Connect/Express NodeMiddleware handlers (supporting synchronous next(), Promise-returning async, callback-async, and next(err) propagation) with per-plugin error isolation. |
| onRequest | (request: Request, context: RequestContextStore) => Promise<Response | void> | Response | void | Optional | Universal Web Standards middleware hook executed sequentially on every incoming HTTP request (including dynamic SSR, cached SSG/ISR/PPR routes, Server Functions, and /____rsc_* SPA fetches; automatically skipped during build-time SSG). Returning a Web Response aborts immediately (<1ms); returning void continues execution and preserves custom properties and context.res mutations for downstream Server Components and Server Functions. |
Execution Lifecycle & Response Contract
Understanding early exit, RSC SPA redirect translation, route normalization, and pipeline pass-through in onRequest.
Response Returned) & SPA RedirectsIf onRequest returns a Web Response (e.g. Response.redirect(), Response.json(), or a custom Response), Dinou terminates the request immediately (<1ms), bypassing cache reads and React rendering while merging any headers/cookies already queued on context.res.
When an onRequest plugin returns a 3xx redirect during an internal /____rsc_* SPA fetch, Dinou automatically translates it into a 200 response with an x-rsc-redirect header while preserving all Set-Cookie headers so client-side navigation redirects cleanly without CORS/opaque-redirect issues. Uncaught exceptions in onRequest are isolated per plugin and return a safe 500 Internal Server Error.
If onRequest returns void (undefined), execution proceeds to route resolution, cached SSG/ISR/PPR delivery, or React rendering. Any custom properties attached to context (e.g. context.user = session) are preserved in AsyncLocalStorage and accessible synchronously via getContext().
Prefer checking context.req.path instead of raw new URL(request.url).pathname when guarding pages: Dinou normalizes context.req.path to the logical route pathname (e.g. "/admin") even on internal /____rsc_page____/admin SPA fetches (exposing the raw wire path in context.req.rawPath and context.req.isRscRequest). onRequest is automatically skipped during build-time SSG.
Production Plugin Patterns
Practical implementations for route/API guards, geolocation enrichment, server-timing telemetry, and Node.js/Bun configureServer integration.
// src/plugins/auth-guard.ts
import type { DinouPlugin } from "dinou";
export const authGuardPlugin: DinouPlugin = {
name: "auth-guard",
async onRequest(request, context) {
// 1. Protect both SSR HTML and SPA RSC navigations using normalized context.req.path
if (context.req.path.startsWith("/admin") && !context.req.cookies.session) {
// Automatically becomes HTTP 302 on SSR and x-rsc-redirect on SPA fetches!
return Response.redirect(new URL("/login", request.url), 302);
}
// 2. Intercept secured API endpoints before React loads
if (context.req.path.startsWith("/api/admin")) {
const authHeader = request.headers.get("authorization");
if (!authHeader || !authHeader.startsWith("Bearer secret_admin_token")) {
// Fast-path early exit: terminates request in <1ms
return Response.json(
{ error: "Forbidden: invalid administrative token" },
{ status: 403, headers: { "Cache-Control": "no-store" } }
);
}
}
},
};// src/plugins/geo-enrichment.ts
import type { DinouPlugin } from "dinou";
export const geoPlugin: DinouPlugin = {
name: "geo-enrichment",
async onRequest(request, context) {
// Extract Edge CDN headers (Cloudflare, Netlify, AWS CloudFront)
const country = request.headers.get("cf-ipcountry") || "US";
const city = request.headers.get("cf-ipcity") || "San Francisco";
// Enrich the request context object with geo metadata
context.geo = {
country,
city,
isEu: ["DE", "FR", "ES", "IT", "NL"].includes(country),
};
// Return nothing (void) -> execution proceeds to React rendering
// Downstream Server Components can read context.geo via getContext()!
},
};// src/plugins/server-timing.ts
import type { DinouPlugin } from "dinou";
export const telemetryPlugin: DinouPlugin = {
name: "server-timing",
async onRequest(request, context) {
const start = performance.now();
// Fast-path health check endpoint
if (context.req.path === "/healthz") {
const duration = (performance.now() - start).toFixed(2);
return Response.json({
status: "healthy",
uptime: typeof process !== "undefined" && process.uptime ? process.uptime() : 0,
latencyMs: Number(duration),
});
}
// Attach request start timestamp for downstream telemetry
context.startTime = start;
},
};// src/plugins/realtime.ts (Node.js & Bun runtimes)
import type { DinouPlugin } from "dinou";
import { WebSocketServer } from "ws";
export const realtimePlugin: DinouPlugin = {
name: "realtime-ws",
configureServer({ server, isDev, use }) {
// 1. Attach WebSockets directly to the underlying http.Server
const wss = new WebSocketServer({ noServer: true });
server.on("upgrade", (req, socket, head) => {
if (req.url === "/ws") {
wss.handleUpgrade(req, socket, head, (ws) => {
ws.send(JSON.stringify({ ready: true, isDev }));
});
}
});
// 2. Register Connect/Express-style raw Node middlewares
use((req, res, next) => {
res.setHeader("X-Powered-By", "Dinou");
next();
});
},
};5. Server Cache & Revalidation (dinou/server)Micro-ISR & Invalidation
revalidatePage()
dinou/serverTarget: Page Component OnlyReturns: Promise<void>Asynchronously invalidates and regenerates only the targeted page component (its page.rsc payload and static index.html, or its Page Static Shell shell.html / shell.rsc on ppr = true routes), while leaving parent and ancestor layouts (layout.rsc) completely untouched. Commits in causal order (_old snapshot → metadata.json → page.rsc → index.html) to guarantee zero React #418 hydration mismatches under concurrent traffic.
Page-Only Invalidation Scope
Why targeted page revalidation saves server compute and bandwidth.
When updating an individual blog post or product price, re-rendering global headers, user navigation menus, and shared footer layouts is unnecessary overhead.
revalidatePage(path) recalculates strictly the page JSX artifact and composes the updated index.html (or shell.html) against the existing cached layout.rsc. In standalone scripts, queue workers, or unit tests without an active RSC runtime, it cleanly evicts the target keys from the active StorageAdapter.
Supports absolute routes (e.g. "/products/laptop-pro") as well as relative paths (e.g. "./", "..", "../overview") inside Server Functions, resolved via x-dinou-current-path (falling back to Referer) without triggering Automatic Static Bailout.
Trailing slashes, ?query strings, and #hash fragments are automatically stripped to guarantee consistent cache keys across Node.js, Bun, Deno, Netlify, and Cloudflare Workers.
| Parameter | Type | Default | Description |
|---|---|---|---|
| path | string | Required | The target route path to revalidate (e.g. "/blog/post-1", "/products/123", or "./" for the active URL). Trailing slashes are automatically normalized. |
// src/actions/update-article.ts
"use server";
import { revalidatePage } from "dinou/server";
import { db } from "@/lib/db";
export async function updateArticle(slug: string, content: string) {
// 1. Update database record
await db.articles.update({ where: { slug }, data: { content } });
// 2. Purge only the article's page.rsc and index.html
// Leaves the parent /blog layout and global navigation cache untouched
await revalidatePage(`/blog/${slug}`);
return { success: true };
}// src/plugins/cms-webhook.ts
import type { DinouPlugin } from "dinou";
import { revalidatePage } from "dinou/server";
export const cmsWebhookPlugin: DinouPlugin = {
name: "cms-webhook",
async onRequest(request) {
const url = new URL(request.url);
if (url.pathname === "/api/webhooks/cms" && request.method === "POST") {
const payload = await request.json();
const slug = payload?.entry?.slug;
if (slug) {
// Invalidate strictly the updated page without rebuilding shared layouts
await revalidatePage(`/posts/${slug}`);
return Response.json({ revalidated: true, path: `/posts/${slug}` });
}
return Response.json({ error: "Missing slug" }, { status: 400 });
}
},
};revalidateLayout()
dinou/serverTarget: Layout Segment Only (O(1))Returns: Promise<boolean>Asynchronously invalidates and regenerates only the targeted layout segment (layout.rsc and layout.metadata.json) in O(1) time without re-executing any child page.tsx components. Concurrent calls to the same layout are automatically deduplicated in-flight, previous snapshots are backed up to layout._old.rsc, and affected child index.html documents and nested sub-layouts are lazily re-composed on demand when next visited — guaranteeing zero hydration mismatches on hard browser reloads (F5).
O(1) Layout Invalidation & Lazy HTML Re-composition
How Dinou updates shared layouts across thousands of child routes with zero page re-executions.
When a shared sidebar, header, or segment layout changes, calling revalidateLayout(path) re-runs strictly that segment's layout_functions.ts (getProps, getCacheTags) and layout.tsx to persist a fresh layout.rsc with monotonic generatedAt and layoutGeneratedAt timestamps.
On ppr = true routes, it regenerates only the Layout Static Shell while keeping dynamic <Suspense> holes in the layout streaming live per request.
Soft SPA navigations immediately consume the fresh layout.rsc. When a child route (e.g. /docs/routing) is next requested via a hard reload (F5), Dinou detects that an ancestor layout's generatedAt is newer than the child's cached generatedAt.
Dinou then lazily re-composes the child's index.html on the fly by splicing its existing cached page.rsc into the fresh layout.rsc — without re-running the child's page.tsx or resetting its own pageGeneratedAt ISR countdown.
| Parameter | Type | Default | Description |
|---|---|---|---|
| path | string | Required | The route segment path whose layout should be revalidated (e.g. "/" for the root layout, "/docs", "/dashboard", or relative paths like "./", "..", "../billing" inside Server Functions). Trailing slashes, ?query, and #hash are automatically stripped. Resolves to true if a layout existed at that segment and was regenerated/evicted, or false otherwise. |
Nested Sub-Layout Propagation
/ or /dashboard) is invalidated via revalidateLayout(), any deeper nested sub-layouts (e.g. /dashboard/settings/layout.tsx) also lazily update their cumulative layout.rsc on demand the next time a route in that sub-branch is visited.// src/actions/sidebar-actions.ts
"use server";
import { revalidateLayout } from "dinou/server";
import { db } from "@/lib/db";
export async function reorderDocsSidebar(newOrder: string[]) {
// 1. Persist the updated sidebar navigation order
await db.navigation.updateOrder("docs-sidebar", newOrder);
// 2. O(1) Surgical Layout Invalidation:
// Regenerates ONLY /docs/layout.rsc (0 child doc pages are re-executed).
// All child routes (/docs/routing, /docs/rendering, etc.) lazily re-compose
// their index.html on demand using their cached page.rsc payloads.
await revalidateLayout("/docs");
return { success: true };
}// src/plugins/announcement-webhook.ts
import type { DinouPlugin } from "dinou";
import { revalidateLayout } from "dinou/server";
export const announcementWebhookPlugin: DinouPlugin = {
name: "announcement-webhook",
async onRequest(request) {
const url = new URL(request.url);
if (url.pathname === "/api/webhooks/banner" && request.method === "POST") {
// Regenerate the global root layout (src/layout.tsx) in O(1) time
// without rebuilding every page across the application
const updated = await revalidateLayout("/");
return Response.json({ revalidated: updated, scope: "root-layout" });
}
},
};revalidatePath()
dinou/serverTarget: Segment Layout + PageReturns: Promise<void>Asynchronously invalidates and regenerates both the segment layout (layout.rsc, whenever a layout is cached or a layout.tsx exists at that segment) and the route page (page.rsc and index.html / shell.html) for the specified URL. Internally, it executes revalidateLayout(path) first so revalidatePage(path) composes immediately against the fresh layout.
Parameters & Segment Scope
Parameters accepted by revalidatePath(path).
| Parameter | Type | Default | Description |
|---|---|---|---|
| path | string | Required | The target route path to revalidate (e.g. "/docs", "/store", or relative paths like "./" / "../dashboard" inside Server Functions, resolved via x-dinou-current-path). Trailing slashes, ?query, and #hash are stripped automatically. Regenerates that segment's layout.rsc (if present) and its page.rsc + index.html. |
| options | { cascade?: boolean } | "layout" | Deprecated | Deprecated & ignored since v9.0.3. Zero hydration mismatch across child routes is now guaranteed automatically via lazy on-demand index.html re-composition. For layout-only invalidation without re-executing the index page, use revalidateLayout(path). |
Choosing Between revalidatePath, revalidatePage, and revalidateLayout
revalidatePath(path) when a mutation updates both a segment's layout (layout.tsx) and its index page (page.tsx) simultaneously. If only the page content changed, prefer revalidatePage(path) to avoid regenerating the layout. If only the shared layout changed, prefer revalidateLayout(path) for O(1) layout regeneration; all child subroutes sharing that layout will automatically re-compose their index.html lazily on demand using their cached page.rsc payloads.// src/actions/store-actions.ts
"use server";
import { revalidatePath } from "dinou/server";
import { db } from "@/lib/db";
export async function launchSeasonalCampaign(campaignId: string) {
// 1. Activate campaign in database (affects both banner layout and featured grid)
await db.campaigns.activate(campaignId);
// 2. Revalidate both src/store/layout.tsx (layout.rsc) AND src/store/page.tsx (page.rsc + index.html).
// Child product routes (/store/shoes, /store/hats) lazily re-compose their index.html
// on demand with the new store layout without re-running their page queries.
await revalidatePath("/store");
return { success: true };
}// src/actions/workspace-actions.ts
"use server";
import { revalidatePath } from "dinou/server";
import { db } from "@/lib/db";
export async function renameWorkspace(workspaceId: string, name: string) {
await db.workspaces.update({ where: { id: workspaceId }, data: { name } });
// Revalidates both the active URL's segment layout and page
// using relative path resolution from the current request context
await revalidatePath("./");
return { success: true };
}revalidateTag()
dinou/serverMulti-Target Global RevalidationReturns: Promise<void>Purges and regenerates all route pages, segment layouts, and independent <DinouCacheSlot> fragments matching the specified cache tag (or slot id) across the application. Records distributed invalidation timestamps via storage.markTagInvalidatedAsync(tag) so cold pods and sibling cluster replicas never resurrect stale build-time .dinou/dist2 artifacts.
Parameters & Tag Resolution
Parameters accepted by revalidateTag(tag).
| Parameter | Type | Default | Description |
|---|---|---|---|
| tag | string | Required | The cache tag identifier to invalidate (e.g. "products", "site-nav", or dynamic entity tags like "product-42"). Matches against tags declared via getCacheTags (static arrays or dynamic (params) => string[] functions) in page_functions.ts and layout_functions.ts, as well as id, tag, and tags props on <DinouCacheSlot> — even across cold restarts and distributed pods. |
| options | { cascade?: boolean } | "layout" | Deprecated | Deprecated & ignored since v9.0.3. Matched layouts automatically trigger lazy on-demand index.html re-composition across child routes to guarantee 0 hydration mismatch without eager cascading. |
Unified Cross-Tier Invalidation (Slot → Ancestor Layout → Page)
revalidateTag() resolves storage artifacts across all three segmentation axes in deterministic order:- 1. Micro-ISR Slots (
<DinouCacheSlot>): Matching cache slot payloads (byid,tag, ortags) are evicted first. If a matched slot resides inside a Static Shell (e.g. an unwrapped slot or a<Suspense>+noDynamic()slot on appr = trueroute), Dinou surgically splices the refreshed slot into the host page or layout shell (onlyRefreshSlots: true) without re-executingpage.tsx/layout.tsxor resetting host ISR TTLs (pageGeneratedAt/layoutGeneratedAt). - 2. Segment Layouts (
layout_functions.ts): Matched layouts executerevalidateLayout()in ancestor-first order (O(1) per segment), updatinglayout.rscwhile child routes lazily re-compose theirindex.htmlon demand. - 3. Route Pages (
page_functions.ts): Matched routes (including dynamic routes like/products/[id]) executerevalidatePage(), regeneratingpage.rscandindex.htmlwhile composing with the freshly updated layout chain.
// src/catalog/page_functions.ts
import type { PageFunctions } from "dinou";
// 1. Tag the entire route page for broad invalidation
export const getCacheTags: PageFunctions["getCacheTags"] = [
"catalog",
"products",
];
// Background fallback TTL (1 hour)
export const revalidate: PageFunctions["revalidate"] = 3600;// src/catalog/page.tsx
import { DinouCacheSlot } from "dinou/server";
import { ProductGrid } from "@/components/product-grid";
import { RealtimeStock } from "@/components/realtime-stock";
export default async function CatalogPage() {
return (
<main className="container mx-auto py-8">
<h1>Product Catalog</h1>
{/* Static product listings */}
<ProductGrid />
{/* 2. Micro-ISR cache slot with granular tags */}
<DinouCacheSlot
id="inventory-feed"
tags={["inventory", "products"]}
revalidate={60}
>
<RealtimeStock />
</DinouCacheSlot>
</main>
);
}// src/actions/inventory-actions.ts
"use server";
import { revalidateTag } from "dinou/server";
import { db } from "@/lib/db";
export async function restockItem(productId: string, quantity: number) {
// 1. Mutate database records
await db.stock.increment(productId, quantity);
// 2. Targeted Slot Invalidation:
// Regenerates only <DinouCacheSlot> components tagged with "inventory"
// and splices the updated fragment into the cached catalog shell
// without re-running CatalogPage or ProductGrid.
await revalidateTag("inventory");
return { success: true };
}
export async function bulkPriceUpdate(categoryId: string) {
await db.pricing.applyDiscount(categoryId, 0.15);
// Broad Multi-Tier Invalidation:
// Regenerates all catalog pages, layouts, and inventory slots tagged with "products".
await revalidateTag("products");
return { success: true };
}| Function | Target Scope | Layout Affected? | Child Routes HTML Strategy | Best Used For |
|---|---|---|---|---|
| revalidatePage(path) | Single route page artifact (page.rsc, index.html / shell.html) | No | None (rebuilds only target URL) | Specific page mutations, article edits, and single-record updates where shared layouts remain untouched. |
| revalidateLayout(path) | Segment layout shell only (layout.rsc, O(1) execution) | Yes (O(1)) | Lazy on-demand index.html re-composition (0 child page.tsx runs) | Shared navigation bars, sidebars, user headers, or global announcements shared across many child routes. |
| revalidatePath(path) | Segment layout (layout.rsc) AND index page (page.rsc, index.html) | Yes (if present) | Immediate for path; lazy on-demand for child subroutes | Mutations that update both a section's shared layout and its index landing page simultaneously. |
| revalidateTag(tag) | All pages, layouts, and <DinouCacheSlot> fragments matching tag | If tagged | Lazy on-demand for tagged layouts; surgical shell splicing for Static Shell slots | Cross-cutting domain mutations (e.g. inventory stock, product catalog, CMS categories) spanning multiple routes and slots. |
<DinouCacheSlot>
Server PrimitiveReturns: Promise<ReactNode>The foundational primitive for Micro-ISR (Vertical 3D Segmentation) in React Server Components. Allows isolating, caching, and revalidating independent component subtrees within an active page or layout without re-evaluating the parent route, re-fetching unchanged database queries, or resetting client component state.
Props & Micro-ISR Reference
Configuring TTL revalidation, cache tags, and targeted slot identifiers.
| Prop | Type | Default | Description |
|---|---|---|---|
| id | string | Optional | Unique identifier for targeted client-side slot refreshing via refreshSlot(id) or router.refreshSlot(id), server-side revalidateTag(id), and the primary storage key (slots/<id>/slot.json + slot.metadata.json). When caching personalized data, parameterize the ID (e.g. id={`cart-${userId}`}). If omitted, Dinou falls back to tag or tags[0]. |
| revalidate | number | false | undefined (Forever) | Time-based Micro-ISR TTL in seconds. When >= 1, serves from storage and refreshes in the background once expired. When < 1 (e.g. 0), bypasses server cache storage (always renders fresh, triggering a Dynamic PPR Hole inside <Suspense> on PPR routes or Automatic Static Bailout on non-PPR routes) while still registering the slot for surgical client-side refreshSlot(id) updates. When false or omitted, caches indefinitely until revalidateTag() or refreshSlot(id, { fresh: true }). |
| tag / tags | string / string[] | undefined | Single cache tag or array of tags for server-side on-demand invalidation via revalidateTag(tag) (if both tag and tags are provided, Dinou merges and deduplicates them automatically alongside id). |
| children | ReactNode | (() => Promise<ReactNode> | ReactNode) | Required | The Server Component subtree to isolate, render, and cache independently. Accepts standard JSX elements or a deferred asynchronous render function (() => Promise<ReactNode>). |
Dinou executes the slot's child components once (deduplicating concurrent in-flight renders), serializes the resolved JSX tree into slots/<id>/slot.json in your storage backend (Redis, Memory, KV, or FileSystem), and serves that cached payload to subsequent visitors without re-running database queries until TTL expiry or invalidation.
When a slot refreshes (via refreshSlot(id), time-based Micro-ISR, or revalidateTag), only that specific subtree updates in the browser DOM and in any host Static Shell (shell.html / index.html) without re-executing page.tsx / layout.tsx or resetting the host segment's own pageGeneratedAt / layoutGeneratedAt ISR countdown.
PPR & ISG Synergy: Nesting Order with <Suspense>
ppr mode determine how a slot integrates with Static Shells and Dynamic Holes:ppr = true+<Suspense><DinouCacheSlot>...</DinouCacheSlot></Suspense>(Cached Dynamic PPR Hole): The fallback is sent in the 0ms Static Shell, while the slot resolves asynchronously and streams from the Micro-ISR cache.ppr = false+<Suspense><DinouCacheSlot revalidate={60}>...</DinouCacheSlot></Suspense>(Static / ISG Safe): Stays 100% static without triggering Automatic Static Bailout — both the page and slot cache normally via SSG/ISG unless the slot setsrevalidate={0}or accesses dynamic request data.- Unwrapped
<DinouCacheSlot>(or withnoDynamic()): Baked directly into the 0ms Static Shell (shell.html) and surgically spliced in storage whenever invalidated.
Production Slot Patterns
Explore real-world patterns for independent TTLs, parameterized user slots, and multi-slot dashboards.
// src/components/crypto-ticker-slot.tsx (Server Component)
import { DinouCacheSlot } from "dinou/server";
import { fetchCryptoPrices } from "@/lib/crypto";
export function CryptoTickerSection() {
return (
<div className="border rounded-lg p-4 bg-card">
<h2 className="text-sm font-semibold mb-2">Live Market Watch</h2>
{/* Caches ticker independently for 15 seconds */}
<DinouCacheSlot id="crypto-ticker" revalidate={15} tag="crypto">
<LiveCryptoPrices />
</DinouCacheSlot>
</div>
);
}
async function LiveCryptoPrices() {
const prices = await fetchCryptoPrices();
return (
<div className="flex gap-4 font-mono text-xs">
<span>BTC: ${prices.btc.toLocaleString()}</span>
<span>ETH: ${prices.eth.toLocaleString()}</span>
<span>SOL: ${prices.sol.toLocaleString()}</span>
</div>
);
}// src/components/cart-badge-slot.tsx (Server Component)
import { Suspense } from "react";
import { DinouCacheSlot, getContext } from "dinou/server";
import db from "@/lib/db";
export function CartBadgeSlot() {
// Wrap the component that reads cookies inside <Suspense> so PPR routes
// keep the surrounding page/layout static while streaming the user's cart!
return (
<Suspense fallback={<span className="badge opacity-50">...</span>}>
<PersonalizedCartSlot />
</Suspense>
);
}
function PersonalizedCartSlot() {
const ctx = getContext();
const userId = ctx.req.cookies.user_id || "guest";
return (
/* Parameterized ID & tags isolate each user's cached cart fragment */
<DinouCacheSlot
id={`header-cart-${userId}`}
tags={[`cart-${userId}`, "cart"]}
>
<CartCounter userId={userId} />
</DinouCacheSlot>
);
}
async function CartCounter({ userId }: { userId: string }) {
const count = await db.cart.getItemCount(userId);
return <span className="badge font-bold">{count} items</span>;
}// src/dashboard/page.tsx (Server Component)
import { DinouCacheSlot } from "dinou/server";
import { UserMetrics } from "@/components/metrics";
import { GlobalAnnouncements } from "@/components/announcements";
import { ActivityFeed } from "@/components/activity";
export default function DashboardPage() {
return (
<div className="space-y-6">
<header>
<h1 className="text-2xl font-bold">Workspace Overview</h1>
</header>
{/* Slot A: Global announcements cached for 1 hour */}
<DinouCacheSlot id="announcements" revalidate={3600} tag="announcements">
<GlobalAnnouncements />
</DinouCacheSlot>
<div className="grid grid-cols-3 gap-6">
{/* Main Content: High-velocity metrics cached for 30s */}
<div className="col-span-2">
<DinouCacheSlot id="metrics" revalidate={30} tag="metrics">
<UserMetrics />
</DinouCacheSlot>
</div>
{/* Sidebar: Activity feed revalidated on-demand via revalidateTag("activity-feed") */}
<div>
<DinouCacheSlot id="activity" tags={["activity-feed"]}>
<ActivityFeed />
</DinouCacheSlot>
</div>
</div>
</div>
);
}noDynamic()
PPR Control PrimitiveReturns: voidOpts an enclosing <Suspense> boundary out of becoming a Dynamic PPR Hole when wrapping an asynchronous Server Component on a ppr = true route. Exported from "dinou", contextual "./dinou", and "dinou/server" (safe no-op in browser environments). Calling noDynamic() synchronously at the top of an async component (before its first await) instructs Dinou to resolve the promise at build/revalidation time and bake the rendered output directly into the Static Shell (shell.html).
On ppr = true routes, Dinou normally treats every <Suspense> boundary wrapping an async component as a dynamic hole to be streamed per request.
When noDynamic() is called synchronously before the first await, Dinou bakes the boundary into the Static Shell at build/revalidation time and immediately short-circuits it in 0ms during runtime PPR hole traversal without re-running its async queries.
Ideal when a shared component is wrapped in <Suspense> for non-PPR routes or third-party library compatibility, or when combining <Suspense> with <DinouCacheSlot> to keep a slot inside the 0ms Static Shell while still allowing independent Micro-ISR refreshes.
Call Synchronously Before the First await
noDynamic() must be invoked synchronously at the very start of your async Server Component (or inside a <DinouCacheSlot> render callback) before any await expression yields control to the event loop.// src/docs/page.tsx (ppr = true route)
import { Suspense } from "react";
import { noDynamic } from "dinou/server";
import { fetchChangelog } from "@/lib/cms";
export default function DocsOverviewPage() {
return (
<main className="space-y-6">
<h1>Documentation</h1>
{/* Even though wrapped in <Suspense> on a ppr = true route,
noDynamic() bakes <ReleaseNotes /> directly into shell.html */}
<Suspense fallback={<div>Loading notes...</div>}>
<ReleaseNotes />
</Suspense>
</main>
);
}
async function ReleaseNotes() {
// Must be called synchronously BEFORE the first await!
noDynamic();
const notes = await fetchChangelog();
return <article>{notes.summary}</article>;
}// src/blog/page.tsx (ppr = true route)
import { Suspense } from "react";
import { DinouCacheSlot, noDynamic } from "dinou/server";
import { fetchTopAuthors } from "@/lib/db";
export default function BlogPage() {
return (
<Suspense fallback={<div>Loading authors...</div>}>
<DinouCacheSlot id="top-authors" revalidate={300} tag="authors">
<TopAuthorsWidget />
</DinouCacheSlot>
</Suspense>
);
}
async function TopAuthorsWidget() {
// Opts the outer <Suspense> + <DinouCacheSlot> into the Static Shell (shell.html)
// while preserving independent 300s Micro-ISR and revalidateTag("authors") splicing!
noDynamic();
const authors = await fetchTopAuthors();
return (
<ul>
{authors.map((a) => (
<li key={a.id}>{a.name}</li>
))}
</ul>
);
}6. Storage Adapters (dinou/server)Storage Abstraction & Persistence
Dinou completely decouples ISR and Micro-ISR caching logic from physical storage media. All pre-rendered HTML, RSC route payloads, segment layouts, and slot fragments are read and written through a unified StorageAdapter interface.
Switch between local disk, distributed memory caches, edge KV stores, or custom object storage without modifying application components or data loaders.
Every cached entry preserves associated metadata, including generation timestamps (generatedAt), assigned cache tags, and ISR revalidation windows.
In multi-instance setups (Kubernetes, Cloud Run, Edge workers), adapters like RedisStorage or CloudflareKVStorage share generated artifacts globally across all nodes.
Built-In Adapters Reference
Production storage engines available directly from dinou/server.
| Adapter Class | Constructor Signature | Metadata Strategy | Target Environment |
|---|---|---|---|
| FileSystemStorage | new FileSystemStorage(baseDir?: string) | Writes companion metadata.json, layout.metadata.json, and slot.metadata.json files alongside cached payloads. | Local development, single-node Node.js / Bun / Docker / VPS servers (default: .dinou/dist2). Always used internally during dinou build SSG generation so live Redis clusters are never polluted at build time. |
| RedisStorage | new RedisStorage(redisClient: any, prefixOrOptions?: string | RedisStorageOptions) | Serializes content and metadata as JSON under a configurable key prefix (default: "dinou:cache:"), plus Redis-backed cluster tombstones (__tombstone__:*) and tag invalidation timestamps (__tag_inv__:*). Auto-detects node-redis v4/v5 (scanIterator), ioredis (scanStream), @upstash/redis (keys), and cursor scan clients. | Multi-container Kubernetes clusters, AWS ECS, Google Cloud Run, distributed Node.js / Bun servers. Lazily hydrates cold keys from .dinou/dist2 by default (hydrateFromDisk: true). |
| CloudflareKVStorage | new CloudflareKVStorage(kvNamespace: any) | Leverages Cloudflare KV native metadata attributes via getWithMetadata() and put(..., { metadata }), with automatic cursor pagination in keys() beyond 1,000 keys. | Cloudflare Workers at global edge scale (auto-selected from env.DINOU_CACHE when bound). |
| DenoKVStorage | new DenoKVStorage(kvInstance?: any) | Stores atomic key-value records with automatic 16KB payload chunking for large HTML/RSC artifacts. Auto-opens via DENO_KV_URL, DENO_DEPLOYMENT_ID, or DENO_KV_PATH (default .dinou/kv.db) when omitted. | Deno Deploy & Deno Edge runtimes (auto-selected when Deno.openKv is available). |
| MemoryStorage | new MemoryStorage(options?: MemoryStorageOptions) | Maintains an in-memory JavaScript Map storing { content, metadata } tuples. Defaults to hydrateFromDisk: false for isolated unit tests; pass { hydrateFromDisk: true } to lazily hydrate pre-built .dinou/dist2 files. | Unit testing, ephemeral CI/CD runners, preview sandboxes, and Netlify Functions v2 (auto-configured with hydrateFromDisk: true). |
Dinou exports getStorageAdapter() to access the active storage instance anywhere on the server, and setStorageAdapter(adapter) to dynamically swap the storage engine during initialization or test suites. During dinou build, static generation always writes build artifacts into .dinou/dist2 via FileSystemStorage — your configured production adapter (such as RedisStorage) is bound exclusively at runtime.
StorageAdapter Contract & Methods
Abstract class properties and methods defined on StorageAdapter (with StorageItem = { content: string; metadata?: Record<string, any> | null }).
| Member | Signature / Type | Required? | Description |
|---|---|---|---|
| get(key) | (key: string) => Promise<StorageItem | null> | Yes | Retrieves the cached content string and companion metadata. Returns null on cache miss. |
| set(key, content, metadata?) | (key: string, content: string, metadata?: any) => Promise<void> | Yes | Persists the rendered HTML, RSC stream, or slot JSON alongside its companion metadata object. |
| has(key) | (key: string) => Promise<boolean> | Yes | Fast existence check to verify if a valid cache artifact exists without deserializing full content. |
| delete(key) | (key: string) => Promise<void> | Yes | Removes the targeted cached artifact and associated companion keys/metadata. |
| keys(prefix?) | (prefix?: string) => Promise<string[]> | string[] | Recommended | Enumerates stored artifact keys. Required for revalidateTag() scanning and <DinouCacheSlot> tag/ID resolution across distributed and Edge storage adapters. |
| hydrateFromDisk | boolean (default: true) | Inherited | When true on non-filesystem adapters, cache misses lazily hydrate pre-rendered build-time artifacts from .dinou/dist2 (respecting deletion tombstones and tag invalidation timestamps). Set to false (default on MemoryStorage) to disable disk fallback. |
| isDeleted / isKeyDeleted | (key: string) => boolean | Promise<boolean> | Inherited | Tracks deletion tombstones so invalidated artifacts are never resurrected from .dinou/dist2 or Edge assets. Distributed adapters (like RedisStorage) override isKeyDeleted(key) to check shared cluster tombstones. |
| markTagInvalidated[Async] / getTagInvalidatedAt[Async] | (tag: string) => void | Promise<void> / number | Promise<number> | Inherited | Records and queries per-tag invalidation timestamps used during revalidateTag() and cold-pod disk hydration. Override the *Async variants in custom multi-node adapters to share tag invalidations across replicas. |
Production Configuration & Custom Implementation
Configure distributed caching with built-in adapters like RedisStorage or extend StorageAdapter to implement a custom engine.
// dinou.config.ts
import { defineConfig } from "dinou/config";
import { RedisStorage } from "dinou/server";
import Redis from "ioredis";
// Connect to shared Redis cache (AWS ElastiCache, Upstash, or Redis cluster)
const redis = new Redis(process.env.REDIS_URL || "redis://localhost:6379");
export default defineConfig({
// Share ISR pages and <DinouCacheSlot> fragments across all Docker / K8s replicas
// Accepts either a prefix string or { prefix?, hydrateFromDisk? }
storage: new RedisStorage(redis, {
prefix: "dinou:cache:",
hydrateFromDisk: true,
}),
});// src/lib/storage/sqlite-storage.ts
import { StorageAdapter } from "dinou/server";
import Database from "better-sqlite3";
export class SQLiteStorage extends StorageAdapter {
private db: Database.Database;
constructor(dbPath: string = ".dinou/cache.db") {
super();
this.db = new Database(dbPath);
this.db.exec(`
CREATE TABLE IF NOT EXISTS dinou_cache (
key TEXT PRIMARY KEY,
content TEXT NOT NULL,
metadata TEXT
);
`);
}
async get(key: string) {
const row = this.db
.prepare("SELECT content, metadata FROM dinou_cache WHERE key = ?")
.get(key) as { content: string; metadata: string | null } | undefined;
if (!row) return null;
return {
content: row.content,
metadata: row.metadata ? JSON.parse(row.metadata) : null,
};
}
async set(key: string, content: string, metadata: any = null): Promise<void> {
const metaStr = metadata ? JSON.stringify(metadata) : null;
this.db
.prepare(
"INSERT INTO dinou_cache (key, content, metadata) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET content = excluded.content, metadata = excluded.metadata"
)
.run(key, content, metaStr);
}
async has(key: string): Promise<boolean> {
const row = this.db
.prepare("SELECT 1 FROM dinou_cache WHERE key = ?")
.get(key);
return Boolean(row);
}
async delete(key: string): Promise<void> {
this.db.prepare("DELETE FROM dinou_cache WHERE key = ?").run(key);
}
async keys(prefix: string = ""): Promise<string[]> {
const rows = this.db
.prepare("SELECT key FROM dinou_cache WHERE key LIKE ?")
.all(`${prefix}%`) as { key: string }[];
return rows.map((r) => r.key);
}
}// dinou.config.js
import { defineConfig } from "dinou/config";
import { SQLiteStorage } from "./src/lib/storage/sqlite-storage.js";
export default defineConfig({
// Register custom storage engine declaratively
storage: new SQLiteStorage(".dinou/production-cache.db"),
});// server-bootstrap.ts
import { setStorageAdapter, getStorageAdapter } from "dinou/server";
import { SQLiteStorage } from "./src/lib/storage/sqlite-storage";
// Dynamically override or configure storage during server boot
const customStorage = new SQLiteStorage(".dinou/production-cache.db");
setStorageAdapter(customStorage);
// Inspect active storage adapter
const activeStorage = getStorageAdapter();
console.log("Dinou active storage adapter:", activeStorage.constructor.name);What is the Redis Key Prefix & Options Object?
The optional second parameter in new RedisStorage(redis, prefixOrOptions) accepts either a namespace string (e.g. "dinou:prod:") or a RedisStorageOptions object ({ prefix?: string; hydrateFromDisk?: boolean }):
- Concrete Example: When Dinou caches the page
/catalogwith the default prefix ("dinou:cache:"), the Redis key isdinou:cache:catalog/index.html(alongside cluster tombstones under__tombstone__:and tag invalidation timestamps under__tag_inv__:). - Avoid Collisions: If your Redis server is shared with user sessions, BullMQ queues, or staging environments, customizing
prefixisolates Dinou's keys completely. - Disk Hydration (
hydrateFromDisk): Defaults totrueso cold pods lazily hydrate pre-rendered build-time.dinou/dist2artifacts on first read while honoring cluster tombstones. SethydrateFromDisk: falseif you want strict Redis-only reads.
7. Route Lifecycles & Configpage_functions.ts & layout_functions.ts
Dinou strictly decouples UI components from server-side lifecycle contracts. Route lifecycles are declared in parallel page_functions.ts (or layout_functions.ts) files.
getProps()
Route Lifecycle HookServer Data LoaderReturns: Promise<TProps> | TPropsThe primary server-side data loading contract for routes and layouts (declared in page_functions.ts or layout_functions.ts / layout.functions.ts). Executes exclusively on the server during SSG build, on-demand ISG generation, or runtime request handling (including custom not_found.tsx segments with a companion page_functions.ts). The object returned by getProps is automatically injected as props into the companion Page, NotFound, or Layout component. Calling return redirect(...) inside getProps short-circuits immediately before page or layout JSX renders.
Parameters
Arguments supplied to getProps(params).
| Parameter | Type | Default | Description |
|---|---|---|---|
| params | Record<string, string | string[]> | {} | Parsed dynamic URL parameters defined by route folder naming (e.g. { id: "42" } for [id] or { slug: ["a", "b"] } for catch-all [...slug]). In layouts, receives all segment parameters up to that layout level. Empty on static routes. |
Accessing Request Headers, Cookies, Query & Automatic Static Bailout
getProps receives route parameters as its first argument, you can access incoming HTTP request headers, cookies, query parameters, or platform environment bindings (ctx.env) by calling getContext() directly inside the function. Reading ctx.req.cookies, ctx.req.headers, or ctx.req.query triggers Automatic Static Bailout (switching the route to Dynamic SSR). On ppr = true routes, keep getProps deterministic and move personalized reads inside <Suspense>.// src/products/[id]/page_functions.ts
import type { PageFunctions } from "./dinou";
import { getContext } from "./dinou";
import { db } from "@/lib/db";
export interface ProductPageProps {
product: {
id: string;
title: string;
price: number;
description: string;
};
preferredCurrency: string;
}
// Contextual "./dinou" pre-binds params for "/products/[id]" automatically
// (or import PageFunctions<"/products/[id]", ProductPageProps> from "dinou")
export const getProps: PageFunctions<ProductPageProps>["getProps"] = async (
params
) => {
// 1. Fetch data on the server using route parameters (params.id is typed as string)
const product = await db.products.findById(params.id);
// 2. Read cookies or headers from request context (triggers Dynamic SSR bailout)
const ctx = getContext();
const preferredCurrency = ctx.req.cookies["user_currency"] || "USD";
// 3. Return props passed directly to the companion Page component
return {
product,
preferredCurrency,
};
};// src/products/[id]/page.tsx
import type { PageProps } from "./dinou";
import type { ProductPageProps } from "./page_functions";
// PageProps accepts TProps directly (or PageProps<"/products/[id]", ProductPageProps> from "dinou")
export default function ProductPage({
params,
product,
preferredCurrency,
}: PageProps<ProductPageProps>) {
return (
<main className="container mx-auto py-8">
<h1 className="text-3xl font-bold">{product.title}</h1>
<p className="text-2xl font-semibold mt-2 text-primary">
{preferredCurrency} {product.price.toFixed(2)}
</p>
<p className="mt-4 text-muted-foreground leading-relaxed">
{product.description}
</p>
</main>
);
}// src/[organization]/layout_functions.ts
import type { LayoutFunctions } from "./dinou";
import { getContext, redirect } from "./dinou";
import { db } from "@/lib/db";
export interface OrgLayoutProps {
organization: {
id: string;
name: string;
tier: string;
};
unreadCount: number;
}
// Layouts receive route parameters defined at or above this segment level
export const getProps: LayoutFunctions<OrgLayoutProps>["getProps"] = async (
params
) => {
const org = await db.organizations.findBySlug(params.organization);
if (!org) {
// Immediately short-circuits layout and page rendering
return redirect("/select-organization") as never;
}
const ctx = getContext();
const unreadCount = await db.notifications.countUnread(
org.id,
ctx.req.cookies["user_id"]
);
// Props are injected directly into src/[organization]/layout.tsx
return {
organization: org,
unreadCount,
};
};// src/[organization]/layout.tsx
import type { LayoutProps } from "./dinou";
import type { OrgLayoutProps } from "./layout_functions";
// LayoutProps includes children, segment params, @slots, and custom TProps
export default function OrgLayout({
children,
params,
organization,
unreadCount,
}: LayoutProps<OrgLayoutProps>) {
return (
<div className="min-h-screen flex flex-col">
<header className="border-b px-6 py-4 flex items-center justify-between">
<span className="font-bold">{organization.name}</span>
<span className="text-xs bg-muted px-2 py-1 rounded">
{unreadCount} unread
</span>
</header>
<main className="flex-1 p-6">{children}</main>
</div>
);
}revalidate
Rendering Strategynumber | false | FunctionDefault: false (Static SSG)The single source of truth for route caching and rendering modes. In page_functions.ts, it defines the rendering strategy of that specific page route. In layout_functions.ts, it establishes a baseline caching policy inherited and reconciled across all descendant routes rendered within that layout branch.
| Value | Rendering Strategy | Lifecycle & Caching Behavior |
|---|---|---|
0 (or < 1) | Dynamic SSR | Bypasses the server static storage cache entirely. Dinou renders the component tree fresh on every incoming HTTP request and sends Cache-Control: no-store, no-cache, must-revalidate headers to downstream proxies and browsers. |
>= 1 (e.g. 60) | ISR (Incremental Static Regeneration) | Cached in the configured StorageAdapter for the specified duration in seconds. While valid, requests receive instantaneous cache hits. The first visitor request after TTL expiration receives the stale cache item while Dinou triggers background revalidation without blocking the response. |
false (or omitted) | Static (SSG) | Pre-rendered during build time (or on first demand via ISG) and persisted indefinitely in storage. The static document is served forever until purged explicitly via revalidatePath(), revalidatePage(), or revalidateTag(). |
Function (sync or async) | Dynamic Strategy Evaluation | An executable function returning number | false. Dinou executes this function on the server at runtime, enabling conditional rendering strategies based on environment variables, CMS flags, or runtime configuration. |
Initial HTML Document Reconciliation (Math.min)
index.html on first load or hard refresh), Dinou reconciles multiple revalidate exports along the route hierarchy using Math.min(). The segment specifying the shortest interval takes precedence so the composite HTML shell never serves stale page content. In contrast, during client-side SPA navigation, Horizontal Layered Segmentation keeps layout.rsc and page.rsc on completely decoupled, independent caching planes. If any segment sets revalidate: 0, the initial HTML response is served via Dynamic SSR.Why does Dinou treat Hard Reloads differently from SPA Soft Navigations, and why does route-level regeneration re-render page.rsc while leaving layout.rsc untouched? The answers stem from two architectural principles: HTML is a monolithic composite file, and React 19 client hydration requires strict atomic parity between the server-rendered HTML DOM and its twin Flight RSC payload.
e.g. page: 10s vs. layout: 3600s (1h)
Math.min() stores a 10s TTL in the route's metadata.json. When expired, Dinou atomically regenerates index.html (baking fresh page data) and page.rsc (for client hydration parity). layout.rsc remains 100% untouched in storage.
The client router retains layout.rsc in memory for the full 1h. Page transitions only fetch the lightweight page.rsc. Zero Layout Overhead — 0ms server CPU is spent recalculating layouts on page transitions.
Only the specific URL (/blog/post-1) expires at 10s. Sibling pages sharing that layout maintain their own independent TTLs.
e.g. layout: 10s vs. page: 3600s (1h)
When the layout's 10s TTL expires (layoutGeneratedAt), Dinou regenerates strictly layout.rsc in O(1) time via revalidateLayout() and lazily re-composes index.html by splicing the child's existing cached page.rsc into the fresh layout — 0 child page.tsx executions, preserving the page's independent pageGeneratedAt 1h countdown!
layout.rsc expires every 10s on its own segmented endpoint. When a client performs a cross-segment transition, the server re-renders only the layout without touching already-cached child pages.
The layout's 10s interval ensures no child route under this branch ever serves a stale layout shell in index.html, while each child page keeps its own 1h data lifetime.
In full-stack React Server Components, pre-rendered HTML and client Flight streams cannot drift out of sync. Dinou's revalidation engine (cache-revalidate.js) commits artifacts in strict causal order (_old snapshot → metadata.json → page.rsc → index.html) with concurrent stampede deduplication, ensuring that when React 19 calls hydrateRoot() in the browser, the Flight stream matches the HTML __DINOU_BUILD_ID__ cleanly with zero #418 hydration mismatches.
// src/products/page_functions.ts
import type { PageFunctions } from "./dinou";
// Time-based ISR: Cache rendered HTML for 60 seconds
// Next request after 60s triggers asynchronous background revalidation
export const revalidate: PageFunctions["revalidate"] = 60;// src/cart/page_functions.ts
import type { PageFunctions } from "./dinou";
// Dynamic SSR: Bypasses static cache completely
// Freshly renders on every request with Cache-Control: no-store headers
export const revalidate: PageFunctions["revalidate"] = 0;// src/pricing/page_functions.ts
import type { PageFunctions } from "./dinou";
// Dynamic evaluation: Switch caching strategy based on runtime environment
export const revalidate: PageFunctions["revalidate"] = async () => {
// Disable caching during local development or staging audits
if (process.env.NODE_ENV !== "production") {
return 0; // Dynamic SSR
}
// Cache for 10 minutes in production
return 600; // ISR 10m
};// src/dashboard/layout_functions.ts
import type { LayoutFunctions } from "./dinou";
// Sets a 5-minute TTL for the /dashboard layout segment (layout.rsc).
// Child pages reconcile initial HTML freshness via Math.min() while keeping
// their own independent page.rsc TTLs (lazy HTML re-composition on layout refresh).
export const revalidate: LayoutFunctions["revalidate"] = 300;ppr
Partial PrerenderingPPRConfigDefault: false (Segment-Isolated)Configures Partial Prerendering (PPR) for an individual page segment, an individual layout segment, or globally in dinou.config.ts. PPR combines the instantaneous response time of static delivery with the flexibility of server-rendered dynamic data. Dinou immediately transmits a pre-rendered static HTML shell (shell.html) and streams dynamic <Suspense> holes concurrently over the same HTTP response stream as they resolve. (Call noDynamic() synchronously before the first await inside an async Server Component to bake a <Suspense> boundary into the static shell instead of streaming it.)
| Scope | Declaration Location | Behavior & Precedence |
|---|---|---|
| 1. Global Config | dinou.config.ts | Sets the application-wide default via defineConfig({ ppr: true }). Every layout and page without an explicit own ppr export falls back directly to this global value (false if omitted). |
| 2. Layout Segment | layout_functions.ts | Controls PPR strictly for that specific layout segment (e.g. streaming dynamic <Suspense> holes in a header/sidebar). Does not cascade to nested child layouts or child pages; each segment evaluates segment.ppr ?? Boolean(dinouConfig.ppr) independently. |
| 3. Page Segment | page_functions.ts | Explicitly opts that page segment into PPR (true) or opts out (false) relative to dinou.config.ts. A composite HTML route streams via PPR whenever the page or any active layout segment resolves to true. |
Critical Architectural Boundary (getProps vs React Suspense)
getProps() executes on the server before React rendering commences, operating entirely outside of React <Suspense> boundaries. Accessing dynamic request parameters, headers, or cookies directly inside getProps() prevents the generation of a static shell, causing Dinou to bail out into Dynamic SSR. To maximize PPR performance, return only deterministic or static shell data from getProps(), and isolate dynamic personalized data inside asynchronous Server Components wrapped with <Suspense fallback={<Skeleton />}>.// src/dashboard/page_functions.ts
import type { PageFunctions } from "./dinou";
// 1. Literal boolean activation
export const ppr: PageFunctions["ppr"] = true;
// 2. Programmatic evaluation (sync or async function)
// export const ppr: PageFunctions["ppr"] = async () => {
// return process.env.ENABLE_PPR === "true";
// };// src/dashboard/page.tsx
import { Suspense } from "react";
import { UserStatsSkeleton } from "@/components/skeletons";
import { RealtimeMetrics } from "@/components/realtime-metrics";
export default function DashboardPage() {
return (
<div className="p-6 space-y-6">
{/* 1. Static Shell: Rendered at build time and served in 0ms */}
<header className="border-b pb-4">
<h1 className="text-2xl font-bold">Analytics Dashboard</h1>
<p className="text-muted-foreground text-sm">
Overview of workspace activities and live metrics.
</p>
</header>
{/* 2. Dynamic Streaming Hole: Fallback sent in shell, resolved asynchronously */}
<Suspense fallback={<UserStatsSkeleton />}>
<RealtimeMetrics />
</Suspense>
</div>
);
}// src/admin/layout_functions.ts
import type { LayoutFunctions } from "./dinou";
// Segment-isolated enablement: enables PPR strictly for src/admin/layout.tsx
// (e.g. streaming a live notification bell inside <Suspense> in the admin shell).
// Child pages under /admin/* still fall back to dinou.config.ts unless they also opt in.
export const ppr: LayoutFunctions["ppr"] = true;// src/admin/audit/page_functions.ts
import type { PageFunctions } from "./dinou";
// Explicit opt-out when dinou.config.ts sets global defineConfig({ ppr: true })
export const ppr: PageFunctions["ppr"] = false;
// Force fresh Dynamic SSR rendering on every request
export const revalidate: PageFunctions["revalidate"] = 0;getStaticPaths
Static Generation (SSG)StaticPathsResultpage_functions.ts & layout_functions.tsDefines the parameter list for dynamic routes (e.g. [slug], [[category]], [category]/[id], or [...catchall]) to be pre-rendered during build time (SSG). Dinou iterates over the returned paths, executes the component rendering pipeline, and saves the generated HTML and RSC payloads into storage for instant edge delivery.
| Route Segment Type | Valid Return Formats | Example Value |
|---|---|---|
Single Dynamic Segment ([slug] or [id]) | string[], number[], or Record<string, string>[] | ["getting-started", "migration"] or [{ slug: "getting-started" }] |
Optional Single Segment ([[category]]) | (string | number | undefined)[] or Record<string, string | number | undefined>[] | [undefined, "electronics"] (undefined pre-renders the root path) |
Multi-Segment Hierarchy ([category]/[id]) | Record<string, string | number>[] | [{ category: "tech", id: "42" }] |
Catch-all Dynamic Route ([...slug]) | string[][] or { slug: string[] }[] | [["docs", "getting-started"]] |
Optional Catch-all ([[...slug]]) | (string[] | undefined)[] or { slug: string[] }[] | [[], ["features"]] (empty array represents root index) |
Perimeter Coordination with allowISG
getStaticPaths works in direct coordination with allowISG. When allowISG: true (the default), paths defined in getStaticPaths are pre-generated during build time, while unlisted dynamic paths requested by visitors are generated on-demand via Incremental Static Generation (ISG). When allowISG: false, any request for a path not pre-rendered by getStaticPaths immediately triggers a 404 response without executing server rendering.No-Gap Rule and Runtime Parameter Guarantees
[[format]] or [[...tags]]) can be set to undefined only if all subsequent segments along the URL path are also undefined. Specifying an undefined segment followed by a defined segment (e.g. [undefined, "something"]) creates an illegal URL gap and causes Dinou to skip the invalid route during build generation.[[category]]). When visiting the root path, params.category is strictly undefined rather than an empty string or null. This allows JavaScript ES6 default destructuring to apply cleanly in page.tsx.[[...slug]]). params.slug is guaranteed to always be an array (string[]). For the root path, Dinou supplies an empty array [] instead of undefined, allowing safe execution of array operations such as params.slug.join("/") without defensive guards. In getStaticPaths, pre-render the root route with [] (or undefined, which Dinou normalizes to []), never [undefined].Pass-Through Segments. When intermediate dynamic folders lack their own page.tsx, the terminal leaf page_functions.ts supplies parameter objects mapping all dynamic keys at once.
Chain of Responsibility. When both parent and child folders contain a page.tsx, the parent acts as a gatekeeper. If the parent returns an empty array [], traversal stops and child pages are not built. When both return paths, Dinou automatically pre-renders their Cartesian product.
Downward Route Propagation. Parameter combinations generated by getStaticPaths automatically cascade to nested static subpages (such as /blog/[slug]/details) without requiring duplicated exports.
Terminal Catch-all Constraint. Because catch-all segments ([...slug] and [[...slug]]) greedily consume all remaining URL path tokens, they must always be declared as the final terminal segment of a directory path.
Architectural Roles of getStaticPaths in layout_functions.ts
getStaticPaths in layout_functions.ts is supported across all dynamic bracket types ([param], [[param]], [...slug], and [[...slug]], such as /[lang]/layout.tsx, /[[locale]]/layout.tsx, or /docs/[version]/layout.tsx). It fulfills three critical engine functions.getStaticPaths, Dinou automatically injects those parameter combinations into all nested child pages (such as /[lang]/page.tsx, /[lang]/about/page.tsx, and /[lang]/contact/page.tsx). Child pages do not need to duplicate getStaticPaths exports to inherit layout parameters.getStaticPaths in layout_functions.ts instructs the build pipeline to pre-render every variant (such as es/layout.rsc, en/layout.rsc, and fr/layout.rsc) into the storage adapter. During client-side navigation, the browser fetches the pre-rendered layout stream instantly without invoking server execution.allowISG is set to false in a layout, Dinou compiles the layout's getStaticPaths into a strict perimeter set. Incoming requests containing unknown layout parameter values (such as an uncompiled language /de/pricing) are blocked immediately with a 404 response at the layout perimeter before child pages or database operations are executed.The Golden Rule: Where to Define getStaticPaths
getStaticPaths at the exact directory level where the dynamic bracket segment ([param]) is introduced in the filesystem./blog/[slug]/page.tsx where /blog/layout.tsx is static), declare getStaticPaths in page_functions.ts. The layout remains shared across all articles, and the parameter maps directly to individual posts./[lang]/layout.tsx with /about and /contact), declare getStaticPaths in layout_functions.ts. Dinou automatically cascades the defined languages to all nested routes without duplicating exports./[category]/layout.tsx and /[category]/[product]/page.tsx), declare getStaticPaths in both locations. The layout declares valid categories and pre-renders their shells, while the page defines specific product items within those categories.| Route Structure | Declaration Location | Returned Parameter Scope |
|---|---|---|
| /blog/[slug] | [slug]/page_functions.ts | { slug: string } |
| /[lang]/about | [lang]/layout_functions.ts | { lang: string } (cascades to /about) |
| /[category]/[item] | Both layout_functions and page_functions | Layout { category } and Page { category, item } |
PageFunctions<Route> and LayoutFunctions<Route>) enforce parameter shapes automatically and raise compile-time type errors if an unexpected parameter is declared at the wrong hierarchy level.// src/blog/[slug]/page_functions.ts
import type { PageFunctions } from "./dinou";
import { cmsClient } from "@/lib/cms";
// Asynchronous loader fetching dynamic slugs from an external CMS
export const getStaticPaths: PageFunctions["getStaticPaths"] = async () => {
const articles = await cmsClient.getAllArticleSlugs();
// Return an array of strings, numbers, or parameter objects
return articles.map((article) => ({
slug: article.slug,
}));
};// src/products/[[category]]/page_functions.ts
import type { PageFunctions } from "./dinou";
// Optional single segment: pre-renders root /products and category variations
export const getStaticPaths: PageFunctions["getStaticPaths"] = [
undefined, // Pre-renders /products (category is undefined)
"electronics", // Pre-renders /products/electronics
"fashion", // Pre-renders /products/fashion
];// src/shop/[category]/[id]/page_functions.ts
import type { PageFunctions } from "./dinou";
// Parameter objects mapping multiple dynamic segments (strings or numbers)
export const getStaticPaths: PageFunctions["getStaticPaths"] = [
{ category: "electronics", id: "pro-laptop" },
{ category: "electronics", id: 42 },
{ category: "apparel", id: "hoodie" },
];// src/docs/[...slug]/page_functions.ts
import type { PageFunctions } from "./dinou";
import { getAllDocPaths } from "@/lib/content";
// Catch-all segment returning nested string arrays (or { slug: string[] }[])
export const getStaticPaths: PageFunctions["getStaticPaths"] = async () => {
const docRoutes = await getAllDocPaths();
// Example: [["installation"], ["routing", "pages"], ["api", "reference"]]
return docRoutes.map((route) => route.split("/"));
};// src/org/[tenant]/layout_functions.ts
import type { LayoutFunctions } from "./dinou";
import { db } from "@/lib/database";
// Pre-render static paths at the layout level for multi-tenant segments
export const getStaticPaths: LayoutFunctions["getStaticPaths"] = async () => {
const tenants = await db.tenants.findMany({ select: { slug: true } });
return tenants.map((t) => ({ tenant: t.slug }));
};allowISG
Static Generation Controlboolean | (() => boolean | Promise<boolean>)Default: truedinou.config.ts, layout_functions.ts & page_functions.tsControls whether dynamic route segments not pre-rendered during build time by getStaticPaths can be generated on-demand at runtime via Incremental Static Generation (ISG). Configure an application-wide baseline in dinou.config.ts (defineConfig({ allowISG: false })) or override per segment in layout_functions.ts and page_functions.ts. Enforced authoritatively on both direct HTML requests and SPA RSC fetches (/____rsc_page____/* & /____rsc_layout____/*) in root-to-child order.
allowISG: false restricts accessible dynamic URLs strictly to the finite collection declared in getStaticPaths. Any request for a path outside the pre-rendered set immediately returns 404 Not Found without invoking server renderers.Perimeter Coordination with getStaticPaths
allowISG: false, ensure that getStaticPaths exports all valid paths. Incoming requests for dynamic paths absent from the static paths collection will immediately return 404 Not Found.allowISG: false protects server infrastructure against denial-of-service attempts that generate infinite random parameter paths to exhaust build CPU or storage capacity.Branch Enclave and Denial-of-Service Protection in layout_functions.ts
layout_functions.ts, allowISG: false confines accessible layout segments strictly to the collection declared in that layout's getStaticPaths. Requests containing unlisted layout parameters (such as an unknown version in /docs/[version]/guide) trigger an immediate 404 response before child pages are inspected.allowISG: false at the layout boundary, preventing ungenerated layout shells from compiling on demand.// src/blog/[slug]/page_functions.ts
import type { PageFunctions } from "./dinou";
import { getPublishedSlugs } from "@/lib/content";
// 1. Pre-render all published articles during the build phase
export const getStaticPaths: PageFunctions["getStaticPaths"] = async () => {
const slugs = await getPublishedSlugs();
return slugs.map((slug) => ({ slug }));
};
// 2. Strict static enclave: unlisted slugs return 404 immediately
export const allowISG: PageFunctions["allowISG"] = false;
export const getProps: PageFunctions["getProps"] = async (params) => {
return { slug: params.slug };
};// src/products/[id]/page_functions.ts
import type { PageFunctions } from "./dinou";
import { getTopProductIds } from "@/lib/catalog";
// 1. Pre-render the top 100 most popular products at build time
export const getStaticPaths: PageFunctions["getStaticPaths"] = async () => {
const topIds = await getTopProductIds(100);
return topIds.map((id) => ({ id }));
};
// 2. Allow on-demand generation for long-tail products on first visitor request
export const allowISG: PageFunctions["allowISG"] = true;
export const getProps: PageFunctions["getProps"] = async (params) => {
return { id: params.id };
};// src/catalog/[category]/page_functions.ts
import type { PageFunctions } from "./dinou";
// Programmatic ISG flag toggled via environment configuration
export const allowISG: PageFunctions["allowISG"] = () => {
// Disable runtime generation in test or high-load maintenance windows
return process.env.ENABLE_RUNTIME_ISG !== "false";
};
export const getStaticPaths: PageFunctions["getStaticPaths"] = () => [
{ category: "electronics" },
{ category: "apparel" },
{ category: "books" },
];// src/docs/[version]/layout_functions.ts
import type { LayoutFunctions } from "./dinou";
// Define the exact supported documentation versions at build time
export const getStaticPaths: LayoutFunctions["getStaticPaths"] = () => [
{ version: "v1" },
{ version: "v2" },
{ version: "v3" },
];
// Enforce a closed enclave across all child documentation pages
export const allowISG: LayoutFunctions["allowISG"] = false;validateParams()
Perimeter Guard(params?: TParams) => boolean | Promise<boolean>layout_functions.ts & page_functions.tsRoute perimeter guard that evaluates incoming dynamic route parameters before pipeline execution. Returning false immediately terminates the request with a clean 404 Not Found HTTP response without invoking getProps or evaluating downstream components.
getProps executes. Prevents expensive database queries, external API calls, or server load when incoming requests contain malformed, illegal, or malicious parameter inputs.validateParams in layout_functions.ts validates segment parameters (such as organization slugs or project identifiers) and guards the entire subtree, halting requests before any child layout or nested page executes.Authoritative 404 Response and Delivery Veto (HTML & SPA RSC)
validateParams returns false or resolves to false (evaluated on any route or layout segment carrying dynamic parameters), Dinou halts route resolution immediately and responds with a clean 404 Not Found HTTP response.page.rsc / layout.rsc) already exists in storage, returning false vetoes delivery on both direct HTML requests and SPA RSC fetches (/____rsc_page____/* & /____rsc_layout____/*).Subtree Perimeter Guard in layout_functions.ts
layout_functions.ts, validateParams receives exclusively the dynamic parameters of that specific layout segment (for example, params.organization in /[organization]/layout.tsx) rather than downstream child page parameters.false or resolves to false, Dinou halts execution immediately with a 404 response, preventing child layouts, child parameter validations, getProps loaders, and page renderers from running./dashboard, /billing, /settings, and /members) with a single validation hook at the branch root, eliminating redundant validation logic across individual page_functions.ts files.// src/users/[id]/page_functions.ts
import type { PageFunctions } from "./dinou";
// Synchronous perimeter guard rejecting non-numeric parameters
export const validateParams: PageFunctions["validateParams"] = (params) => {
return /^[0-9]+$/.test(params.id);
};
export const getProps: PageFunctions["getProps"] = async (params) => {
// params.id is guaranteed to be a valid numeric string here
return { userId: Number(params.id) };
};// src/documents/[uuid]/page_functions.ts
import type { PageFunctions } from "./dinou";
const UUID_V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
// Rejects malformed UUID tokens before invoking backend loaders
export const validateParams: PageFunctions["validateParams"] = (params) => {
return UUID_V4_REGEX.test(params.uuid);
};// src/[organization]/layout_functions.ts
import type { LayoutFunctions } from "./dinou";
import { db } from "@/lib/database";
// Asynchronous perimeter guard protecting an entire organization branch
export const validateParams: LayoutFunctions["validateParams"] = async (params) => {
const tenant = await db.organizations.findUnique({
where: { slug: params.organization },
select: { active: true },
});
return Boolean(tenant?.active);
};// src/shop/[category]/[slug]/page_functions.ts
import type { PageFunctions } from "./dinou";
const ALLOWED_CATEGORIES = new Set(["electronics", "clothing", "books", "home"]);
// Multi-segment parameter validation ensuring valid taxonomy paths
export const validateParams: PageFunctions["validateParams"] = (params) => {
if (!ALLOWED_CATEGORIES.has(params.category)) {
return false;
}
return /^[a-z0-9-]+$/.test(params.slug);
};