Dinou features 3D Horizontal Layered Segmentation. Route configuration and server lifecycle functions are cleanly decoupled into page_functions.ts (for page.tsx) and layout_functions.ts (for layout.tsx).
In Dinou, every route segment can independently configure its data fetching, static pre-rendering, cache lifecycles, and validation without cluttering component UI code.
Placed alongside page.tsx. Configures data fetching (getProps), static paths, ISR, PPR, and validation specifically for that page.
Placed alongside layout.tsx (also supports layout.functions.ts). Supplies data directly to the layout component and manages segment-level cache strategy independently from child pages.
In Dinou, every server-side configuration file implements the exact same foundational contract: RouteSegmentConfig. This is the framework's underlying "abstract" interface defining all segment capabilities. For day-to-day application code, Dinou exports two concrete, role-based aliases—PageFunctions (for pages) and LayoutFunctions (for layouts)—available both from "dinou" (with explicit route pattern strings) and from each route directory's auto-generated "./dinou" module (with params pre-bound automatically):
// Exported from "dinou" (dinou/index.d.ts):
/**
* Foundational "abstract" interface governing all route segments in Dinou.
*/
export interface RouteSegmentConfig<
TParams = any,
TProps = any,
TStaticPathParams = TParams
> {
// Partial Prerendering (PPR) configuration
ppr?: boolean | (() => boolean | Promise<boolean>);
// Cache & revalidation strategy (< 1 = Dynamic SSR, >= 1 = ISR, false = Static)
revalidate?: number | false | (() => number | false | Promise<number | false>);
// Cache tags for on-demand invalidation via revalidateTag(tag)
getCacheTags?: string[] | ((params?: TParams) => string[] | Promise<string[]>);
// Path generator for SSG (constant array or sync/async function)
getStaticPaths?:
| StaticPathItem<TStaticPathParams>[]
| (() => StaticPathsResult<TStaticPathParams>);
// Server loader providing direct props to the component
getProps?: (params?: TParams) => TProps | Promise<TProps>;
// Parameter validator guard (returns false to halt and return 404)
validateParams?: (params?: TParams) => boolean | Promise<boolean>;
// Controls whether Incremental Static Generation (ISG) is allowed for ungenerated paths
allowISG?: boolean | (() => boolean | Promise<boolean>);
}
/**
* Concrete semantic alias for 'page_functions.ts' (imported from "dinou").
* Accepts a route pattern string (e.g. "/blog/[slug]") or a params dictionary.
* (Or import PageFunctions<TProps> from "./dinou" with RouteParams pre-bound!)
*/
export type PageFunctions<
TRouteOrParams extends DinouRoutePattern | object = any,
TProps = any
> = RouteSegmentConfig<
0 extends 1 & TRouteOrParams
? any
: [TRouteOrParams] extends [DinouRoutePattern]
? RouteParams<Extract<TRouteOrParams, DinouRoutePattern>>
: TRouteOrParams,
TProps,
0 extends 1 & TRouteOrParams
? any
: [TRouteOrParams] extends [DinouRoutePattern]
? StaticPathParams<Extract<TRouteOrParams, DinouRoutePattern>>
: ToStaticPathParams<TRouteOrParams>
>;
/**
* Concrete semantic alias for 'layout_functions.ts' (imported from "dinou").
* Accepts any DinouLayoutPattern (including intermediate layouts without a sibling page.tsx,
* e.g. "/[org]" or "/workspace/[org]") or a params dictionary.
* (Or import LayoutFunctions<TProps> from "./dinou" with LayoutParams pre-bound!)
*/
export type LayoutFunctions<
TRouteOrParams extends DinouLayoutPattern | object = any,
TProps = any
> = RouteSegmentConfig<
0 extends 1 & TRouteOrParams
? any
: [TRouteOrParams] extends [DinouLayoutPattern]
? LayoutParams<Extract<TRouteOrParams, DinouLayoutPattern>>
: TRouteOrParams,
TProps,
0 extends 1 & TRouteOrParams
? any
: [TRouteOrParams] extends [DinouLayoutPattern]
? StaticPathParams<Extract<TRouteOrParams, DinouLayoutPattern>>
: ToStaticPathParams<TRouteOrParams>
>;| Where to use | Type to import | Purpose |
|---|---|---|
| src/.../page_functions.ts | PageFunctions ("./dinou" or "dinou") | Types data loading (getProps), static paths, and cache for the page. |
| src/.../layout_functions.ts | LayoutFunctions ("./dinou" or "dinou") | Types data loading (getProps) and independent cache for the layout shell. |
| Plugins & Shared Utils | RouteSegmentConfig ("dinou") | Base "abstract" interface for generic utilities that process arbitrary route segments. |
import type { PageFunctions } in a page file immediately clarifies intent and self-documents that the functions belong to the page tier.getProps (Direct Component Props)Use getProps to load data on the server based on route params and pass it directly to your component.
getProps directly returns the props object ({ ... }). The legacy wrapper { page: { ... }, layout: { ... } } has been deprecated because pages and layouts now have their own dedicated configuration files.params?: TParams (The normalized dynamic route parameters)TProps | Promise<TProps> (Injected directly as the component's props)use()): getProps can also start non-critical queries without await and return raw Promise properties (e.g. { post, commentsPromise }) so a Client Component wrapped in <Suspense> can unwrap them via React 19's use(commentsPromise) without blocking initial TTFB.redirect("/login") inside getProps immediately aborts rendering of the page/layout and responds with an HTTP 302 redirect (or x-rsc-redirect on SPA navigations).Example: Type-Safe Page Component & Props
// src/blog/[slug]/page_functions.ts
import type { PageFunctions } from "./dinou";
import { db, type Post } from "@/lib/db";
export interface BlogPostData {
post: Post;
}
// "./dinou" pre-binds { slug: string } automatically for this directory
// (or import from "dinou" and write PageFunctions<"/blog/[slug]", BlogPostData>["getProps"])
export const getProps: PageFunctions<BlogPostData>["getProps"] = async (params) => {
const post = await db.getPost(params?.slug);
// Directly returns BlogPostData for page.tsx
return { post };
};// src/blog/[slug]/page.tsx
import type { PageProps } from "./dinou";
import type { BlogPostData } from "./page_functions";
// PageProps<BlogPostData> merges pre-bound { params: { slug: string } } with BlogPostData
// (or import PageProps from "dinou" and write PageProps<"/blog/[slug]", BlogPostData>)
export default function BlogPost({ params, post }: PageProps<BlogPostData>) {
return (
<article>
<span className="text-xs text-muted-foreground">Route: /blog/{params.slug}</span>
<h1>{post.title}</h1>
<div>{post.content}</div>
</article>
);
}Example: Type-Safe Layout Component & Props
// src/blog/layout_functions.ts
import type { LayoutFunctions } from "./dinou";
import { db } from "@/lib/db";
export interface BlogLayoutData {
categories: string[];
}
// "./dinou" pre-binds layout params automatically
// (or import from "dinou" and write LayoutFunctions<"/blog", BlogLayoutData>["getProps"])
export const getProps: LayoutFunctions<BlogLayoutData>["getProps"] = async () => {
const categories = await db.getCategories();
// Directly returns props for layout.tsx
return { categories };
};// src/blog/layout.tsx
import type { LayoutProps } from "./dinou";
import type { BlogLayoutData } from "./layout_functions";
// LayoutProps<BlogLayoutData> types children, params, @slots, and BlogLayoutData
// (or import LayoutProps from "dinou" and write LayoutProps<"/blog", BlogLayoutData>)
export default function BlogLayout({
children,
categories,
}: LayoutProps<BlogLayoutData>) {
return (
<div className="blog-shell">
<BlogSidebar categories={categories} />
<main>{children}</main>
</div>
);
}getProps Only Receives params & The Dynamic Bailout MechanismLearn why Dinou separates route parameters (params) from dynamic request data (cookies, headers, and query params), how accessing them in getProps triggers an automatic switch to dynamic rendering (bailout), and how to stream cookie- or auth-dependent components with React <Suspense> without delaying the initial HTML delivery.
Route params (e.g. /blog/[slug]) identify the resource, not the visitor. Because the content for a given route is identical for everyone, Dinou can run getProps in advance—at build time (SSG) or on first request (ISR)—and safely pre-render and cache the HTML (in static storage, server memory, reverse proxies, or CDNs). In contrast, cookies, headers, and query params belong to a specific HTTP connection. If getProps relied on them, the output could contain private user data, making shared caching impossible and forcing the server to render every request on demand.
Dinou features an automatic bailout mechanism that is essential for cache integrity: it guarantees that personalized or per-request data is never accidentally baked into public static HTML or shared caches. Calling getContext() itself does NOT trigger a bailout; the switch to Dynamic SSR happens only when your code actually reads request-specific properties:
| Property Accessed | Behavior | Why? |
|---|---|---|
| req.cookies | Bailout to Dynamic | Session tokens and user identity vary per request; cannot be cached statically. |
| req.headers | Bailout to Dynamic | Request headers (e.g. authorization, user-agent) are unique per connection. |
| req.query / RSC useSearchParams() | Bailout to Dynamic | URL query parameters (?q=...) read on the server are unconstrained runtime inputs. |
| req.path, req.method, env / Client useSearchParams() | Preserves Static | Normalized segment paths, server/Edge env bindings, and Client Component useSearchParams() stay deterministic and safe for SSG, ISR, PPR, and export-static. |
Inside Server Components, Partial Prerendering (PPR) can isolate dynamic accesses inside <Suspense> boundaries while preserving the static shell. However, getProps executes outside React before component rendering begins. Because getProps is never wrapped by a <Suspense> boundary, reading cookies or query inside getProps forces the entire route to bail out from static generation directly into Dynamic SSR.
With Partial Prerendering (ppr = true), keep the page shell pre-rendered and instant (0ms TTFB) by organizing each data source into its natural layer: route data in getProps, session cookies inside <Suspense>, and query parameters via the universal useSearchParams() hook (in Server Components inside <Suspense>, or in Client Components inside the static shell):
// src/blog/[slug]/page_functions.ts
import type { PageFunctions } from "dinou";
import { db, type Post } from "@/lib/db";
export interface BlogPostData {
post: Post;
}
// Enable PPR so <Suspense> isolates cookies/query holes while preserving the Static Shell
export const ppr: PageFunctions["ppr"] = true;
// 1. Pure route loader: depends solely on params
// Pre-rendered & cached statically for all visitors (SSG / ISR)
export const getProps: PageFunctions<"/blog/[slug]", BlogPostData>["getProps"] = async (params) => {
const post = await db.getPost(params?.slug);
return { post };
};// src/blog/[slug]/page.tsx
import { Suspense } from "react";
import type { PageProps } from "./dinou";
import type { BlogPostData } from "./page_functions";
import { UserSession } from "./user-session";
import { RelatedPosts } from "./related-posts";
import { SearchFilter } from "./search-filter";
export default function BlogPostPage({ params, post }: PageProps<BlogPostData>) {
return (
<article className="post-container">
{/* 1. Instant static shell: delivered immediately from cache (0ms TTFB) */}
<header>
<span className="text-xs text-muted-foreground">Route: /blog/{params.slug}</span>
<h1>{post.title}</h1>
{/* Client Component using useSearchParams(): stays in Static Shell, syncs in browser */}
<SearchFilter />
</header>
<div className="post-body">{post.content}</div>
{/* 2. Dynamic cookie component quarantined & streamed via Suspense (with ppr = true) */}
<Suspense fallback={<div className="text-xs text-muted-foreground">Loading session...</div>}>
<UserSession />
</Suspense>
{/* 3. Server Component using useSearchParams() streamed via Suspense (with ppr = true) */}
<Suspense fallback={<div className="text-xs text-muted-foreground">Filtering articles...</div>}>
<RelatedPosts />
</Suspense>
</article>
);
}// src/blog/[slug]/user-session.tsx (Server Component)
import { getContext } from "dinou";
import { auth } from "@/lib/auth";
// With ppr = true, isolating cookie & auth access inside <Suspense>
// streams user state per request while keeping getProps & the post shell static!
export async function UserSession() {
const sessionToken = getContext().req.cookies.session;
const user = sessionToken ? await auth.verify(sessionToken) : null;
if (!user) {
return <a href="/login" className="text-xs font-semibold">Sign In</a>;
}
return (
<aside className="user-badge">
<span>Welcome back, <strong>{user.name}</strong>!</span>
</aside>
);
}// src/blog/[slug]/related-posts.tsx (Server Component)
import { useSearchParams } from "dinou";
import { db } from "@/lib/db";
// Universal hook in a Server Component (sync or async):
// Reads ctx.req.query on the server. With ppr = true, wrapping it in <Suspense>
// turns this boundary into a Dynamic PPR Hole so the post shell stays static!
export async function RelatedPosts() {
const searchParams = useSearchParams();
const tag = searchParams.get("tag") ?? "featured";
const articles = await db.getPostsByTag(tag);
return (
<section className="related-posts">
<h3>Articles matching "?tag={tag}"</h3>
<ul>
{articles.map((item) => (
<li key={item.id}>{item.title}</li>
))}
</ul>
</section>
);
}// src/blog/[slug]/search-filter.tsx (Client Component)
"use client";
import { useSearchParams } from "dinou";
// Universal hook in a Client Component:
// Stays baked in the Static Shell (does NOT open a server hole), hydrates cleanly
// on any ?tag=... URL, and syncs query params immediately in the browser!
export function SearchFilter() {
const searchParams = useSearchParams();
const currentTag = searchParams.get("tag") ?? "";
return (
<input
key={currentTag}
type="search"
defaultValue={currentTag}
placeholder="Filter by tag (?tag=...)..."
className="text-xs border rounded px-2 py-1"
/>
);
}Handled in getProps. Pure and cacheable for all visitors (SSG/ISR).
With ppr = true, read in Server Components inside <Suspense> to stream without bailing out the static shell.
Works in Server Components (streamed hole inside <Suspense> with ppr = true) and in Client Components (stays in static shell, syncs in browser).
getStaticPaths (Static Generation)Defines which dynamic parameter combinations should be pre-rendered at build time (SSG) in both page_functions.ts and layout_functions.ts (for dynamic layouts). By default, any dynamic path not returned is generated on-demand when first requested and cached statically for all subsequent visitors (Incremental Static Generation / ISG), unless disabled via allowISG: false—either per segment or globally in dinou.config.ts—which strictly restricts that segment to its pre-rendered list and returns 404 for any other path.
In Dinou, getStaticPaths supports both a constant array export (for known, fixed paths) and a synchronous or asynchronous function export (for dynamic data sources like databases or headless CMSs):
Ideal for fixed sets of routes, locales, or documentation sections without extra function execution overhead:
// src/blog/[slug]/page_functions.ts
import type { PageFunctions } from "dinou";
// Best Practice: Type-safe constant array
export const getStaticPaths: PageFunctions<"/blog/[slug]">["getStaticPaths"] = [
"foo",
"bar",
];Ideal for fetching IDs or slugs from external APIs or databases at build time:
// src/blog/[slug]/page_functions.ts
import type { PageFunctions } from "dinou";
import { db } from "@/lib/db";
// Best Practice: Type-safe async function loader
export const getStaticPaths: PageFunctions<"/blog/[slug]">["getStaticPaths"] = async () => {
const ids = await db.getTopProductIds();
return ids;
};Dinou accommodates simple, catch-all, and multi-segment architectures with flexible item formats:
| Route Type | Accepted Format | Example Return |
|---|---|---|
Simple ([id] or [slug]) | string[] | number[] | ["foo", "bar"] or [1, 2, 3] |
Optional Simple ([[id]] or [[slug]]) | (string | number | undefined)[] | [undefined, "foo", "bar"] |
Catch-all ([...slug]) | string[][] | [["a", "b"], ["c"]] |
Optional Catch-all ([[...slug]])* Use [] (empty array) to pre-render the root path | (string[] | undefined)[] | [[], ["a"], ["a", "b"]] |
Nested / Multi-parameter ([category]/[id]) | Record<string, string | number>[] | [{ category: "tech", id: "1" }] |
Complex Nested + Catch-all ([lang]/[category]/[...slug]) | Record<string, string | string[]>[] | [{ lang: "en", category: "api", slug: ["v2", "auth"] }] |
All-Inclusive Matrix (shop/[category]/[id]/[[format]]/[[...tags]])* Respects Dinou's No-Gap Rule (optionals must be trailing) | Record<string, string | number | string[] | undefined>[] | { category: "shoes", id: 42, format: undefined, tags: undefined }→ Pre-renders: /shop/shoes/42{ category: "shoes", id: 42, format: "pdf", tags: ["sale", "pro"] }→ Pre-renders: /shop/shoes/42/pdf/sale/pro |
Simple dynamic routes match a single URL segment. Dinou supports both required segments ([id]) and optional segments ([[category]]):
// src/blog/[id]/page_functions.ts
import type { PageFunctions } from "dinou";
// Best Practice: Type-safe constant array (string[] or number[])
export const getStaticPaths: PageFunctions<"/blog/[id]">["getStaticPaths"] = [
"1",
"2",
"3",
];
// Generates /blog/1, /blog/2, /blog/3// src/shop/[[category]]/page_functions.ts
import type { PageFunctions } from "dinou";
// Pass undefined to pre-render the base route without the segment
export const getStaticPaths: PageFunctions<"/shop/[[category]]">["getStaticPaths"] = [
undefined, // Generates /shop (root path, params.category will be undefined)
"electronics", // Generates /shop/electronics
"clothing", // Generates /shop/clothing
];getStaticPaths: Return undefined to pre-render the base route without the optional segment (e.g. /shop).page.tsx receives: When visiting the root route, params.category is strictly undefined (never an empty string "" or null). This allows native JavaScript ES6 default destructuring to kick in seamlessly: export default function Page({ params: { category = "all" } }: PageProps).Catch-all routes match multiple dynamic path segments. Dinou supports both standard catch-alls ([...slug]) and optional catch-alls ([[...slug]]):
// src/docs/[...slug]/page_functions.ts
import type { PageFunctions } from "dinou";
// Best Practice: Type-safe catch-all segments (string[][])
// Each entry represents an array of path segments
export const getStaticPaths: PageFunctions<"/docs/[...slug]">["getStaticPaths"] = [
["intro"], // Generates /docs/intro
["api", "v1", "auth"], // Generates /docs/api/v1/auth
];// src/docs/[[...slug]]/page_functions.ts
import type { PageFunctions } from "dinou";
// Pass an empty array [] to pre-render the root route (/docs)
export const getStaticPaths: PageFunctions<"/docs/[[...slug]]">["getStaticPaths"] = [
[], // Generates /docs (root path)
["intro"], // Generates /docs/intro
["api", "v1", "auth"], // Generates /docs/api/v1/auth
];getStaticPaths: To pre-render the root page without any segments (e.g. /docs), return an empty array [] (or undefined). Never return [undefined] or [[undefined]].page.tsx receives: In Dinou, params.slug is guaranteed to always be an array (string[]) at both runtime and compile time (PageProps, LayoutProps, and getProps)—while remaining optional when constructing links (<Link href="/docs/[[...slug]]" />) or object entries in getStaticPaths. For the root page, it receives an empty array [] (length 0). It is never undefined, never [undefined], and never a bare string. You can safely call params.slug.join("/") or params.slug.length directly under TypeScript strict: true without defensive checks.Static parameters automatically propagate downwards through the directory tree. If you define values for a segment, Dinou will recursively generate all nested static sub-pages under those values.
src/blog/[slug]/page.tsx (+ page_functions.ts)src/blog/[slug]/details/page.tsx (Nested static page)If getStaticPaths in blog/[slug] returns ["post-a", "post-b"], Dinou automatically generates 4 static pages:
/blog/post-a/blog/post-a/details/blog/post-b/blog/post-b/detailsWhen nesting routes where both the parent and the child segment have their own page.tsx, static generation follows a strict top-down "chain of responsibility":
/shop/[category]/[id]src/shop/[category]/page.tsx (Parent page: /shop/[category])page_functions.ts (Parent gatekeeper)[id]/page.tsx (Child page: /shop/[category]/[id])page_functions.ts (Child loader)Because the parent folder contains a page.tsx, Dinou must generate valid parent pages first before it can traverse down to the child level. The parent acts as a mandatory gatekeeper:
If src/shop/[category]/page_functions.ts returns an empty array []:
/shop/[category]).[] is returned, no parent category folders or HTML files are created.[id]/page_functions.ts, so no child product pages are generated.The parent resolves its own categories first, unlocking the child level:
// 1. Parent: src/shop/[category]/page_functions.ts
import type { PageFunctions } from "dinou";
export const getStaticPaths: PageFunctions<"/shop/[category]">["getStaticPaths"] = [
"shoes",
"shirts",
];
// 2. Child: src/shop/[category]/[id]/page_functions.ts
import type { PageFunctions } from "dinou";
export const getStaticPaths: PageFunctions<"/shop/[category]/[id]">["getStaticPaths"] = [
"100",
"200",
];
// Automatically generates 4 static pages:
// /shop/shoes/100, /shop/shoes/200
// /shop/shirts/100, /shop/shirts/200page.tsx is responsible for opening the door to its descendants. (If an intermediate segment does not have a page.tsx, see Section 2.7 for pass-through segments).When you have multiple dynamic segments in a path without intermediate pages (the intermediate folders do not have a page.tsx), the leaf segment returns an Object mapping all parameter names at once:
// Structure: src/shop/[category]/[brand]/[...specs]/page_functions.ts
// ([category] and [brand] do NOT have their own page.tsx; [...specs] is terminal)
import type { PageFunctions } from "dinou";
export const getStaticPaths: PageFunctions<"/shop/[category]/[brand]/[...specs]">["getStaticPaths"] = [
{
category: "electronics",
brand: "apple",
specs: ["m3", "16gb"],
// → Pre-renders: /shop/electronics/apple/m3/16gb
},
{
category: "clothing",
brand: "nike",
specs: ["running", "shoes", "air"],
// → Pre-renders: /shop/clothing/nike/running/shoes/air
},
];// Structure: src/shop/[category]/[id]/[[format]]/page_functions.ts
// ([category] and [id] do NOT have their own page.tsx; [[format]] is terminal)
import type { PageFunctions } from "dinou";
export const getStaticPaths: PageFunctions<"/shop/[category]/[id]/[[format]]">["getStaticPaths"] = [
{
category: "electronics",
id: "macbook-pro",
format: "json",
// → Pre-renders: /shop/electronics/macbook-pro/json
},
{
category: "clothing",
id: "hoodie",
format: undefined, // Valid: trailing optional segment without trailing gap
// → Pre-renders: /shop/clothing/hoodie
},
];[...slug]) greedily absorbs all remaining path segments to the end of the URL, so it must always be the final folder of a route.[[format]]) can be set to undefined only if all subsequent segments are also undefined. You cannot have an undefined segment followed by a defined one.getStaticPaths can be an async function, allowing you to query external headless CMSs, databases, or REST APIs during the build:
// src/products/[id]/page_functions.ts
import type { PageFunctions } from "dinou";
import { db } from "@/lib/db";
// Best Practice: Type-safe async generator querying a database or CMS
export const getStaticPaths: PageFunctions<"/products/[id]">["getStaticPaths"] = async () => {
// Only pre-generate the top 50 products at build time
const featured = await db.getFeaturedProducts({ limit: 50 });
return featured.map((p) => p.id);
// Any product ID outside the top 50 will be generated
// on-demand when first requested and cached statically (ISG).
};validateParams (Segment Parameter Validation)Validates dynamic parameters (such as [id] or [...slug]) on the server prior to rendering, in both page_functions.ts and layout_functions.ts. If validateParams returns false (or a falsy value), Dinou immediately terminates request processing and issues a 404 Not Found response on both direct URL loads and client-side navigations.
params?: TParams — Normalized dynamic parameters accumulated up to that specific segment (a layout only receives its own accumulated parameters, never deeper child parameters; the leaf page receives all route parameters).boolean | Promise<boolean> (Return false to abort rendering and return 404 Not Found; supports async database or tenant checks).// src/posts/[id]/page_functions.ts
import type { PageFunctions } from "dinou";
// Best Practice: Type-safe segment parameter validation
export const validateParams: PageFunctions<"/posts/[id]">["validateParams"] = (params) => {
// Only allow positive integer IDs; reject malformed requests with 404
return typeof params?.id === "string" && /^\d+$/.test(params.id);
};// 1. Outer Layout: src/[org]/layout_functions.ts
// Receives ONLY { org }
import type { LayoutFunctions } from "dinou";
export const validateParams: LayoutFunctions<"/[org]">["validateParams"] = async (params) => {
return Boolean(params?.org && await db.orgs.exists(params.org));
};
// 2. Nested Layout: src/[org]/projects/[project]/layout_functions.ts
// Receives { org, project } (never deeper child params)
export const validateParams: LayoutFunctions<"/[org]/projects/[project]">["validateParams"] = (params) => {
return Boolean(params?.project && /^[a-z0-9-]+$/.test(params.project));
};
// 3. Leaf Page: src/[org]/projects/[project]/tasks/[task]/page_functions.ts
// Receives all accumulated params: { org, project, task }
import type { PageFunctions } from "dinou";
export const validateParams: PageFunctions<"/[org]/projects/[project]/tasks/[task]">["validateParams"] = (params) => {
return typeof params?.task === "string" && /^\d+$/.test(params.task);
};validateParams is the first line of defense executed by the Dinou server engine in root-to-child order on every incoming request—running ahead of cached static HTML and SPA RSC payloads (/____rsc_page____/*, /____rsc_layout____/*). It has ultimate veto power regardless of whether the route uses pure static (SSG), on-demand (ISG), Partial Prerendering (PPR), or dynamic (SSR) rendering:
Rejects malformed or invalid IDs before on-demand generation starts. Prevents wasteful database queries and stops bots from polluting disk/KV cache with junk pages.
Ultimate veto: even if a static page was pre-rendered by getStaticPaths at build time, returning false immediately blocks delivery with 404, preventing obsolete or revoked pages from being served.
Protects your live server from malicious parameter inputs. Rendering halts and returns 404 before getProps or your layout/page components run.
Just like allowISG, Dinou evaluates validateParams independently per segment along the active layout chain:
In /[org]/projects/[project]/tasks/[task], the [org] layout receives only { org }, the [project] layout receives { org, project }, and the [task] page receives { org, project, task }.
If a nested layout rejects its parameter, every route inside that subtree returns 404 Not Found (on both direct loads and SPA navigations), while sibling routes outside that layout continue responding normally.
When all active layouts pass validation and only the leaf page's validateParams returns false, only that leaf page returns 404 Not Found; parent routes and shared layouts remain unaffected.
Because Dinou walks only the active layout chain, ancestor layouts bypassed via no_layout or above a reset_layout boundary do not run validateParams and never block the route (only the active reset_layout / leaf page validators apply).
/[org]/projects/[project]/tasks/[task]| Scenario | params Received by Failing / Active Validator | Result |
|---|---|---|
All 3 segments return true | { org } → { org, project } → { org, project, task } | 200 OK — Route renders (or caches via SSG/ISG) normally. |
Outer [org] layout returns false | { org: "bad-org" } | 404 Not Found — Entire /bad-org/* subtree is blocked on direct loads & SPA navigations. |
Nested [project] layout returns false | { org: "acme", project: "bad-proj" } | 404 Not Found on /acme/projects/bad-proj/*; sibling /acme stays 200 OK. |
Leaf [task] page returns false | { org: "acme", project: "web", task: "bad" } | 404 Not Found on that task page; parent /acme/projects/web stays 200 OK. |
Subroute uses no_layout or reset_layout under bad-org | Bypassed [org] validator is skipped; active reset_layout / page runs | 200 OK if the active reset_layout / page validator passes (404 if its own validator fails). |
allowISG (On-Demand ISG Control)Controls whether dynamic route segments ([id], [slug], [...catchAll]) that were not pre-rendered at build time (via getStaticPaths during dinou build) are allowed to be generated and cached on-demand on the first incoming user request. It is supported in both page_functions.ts and layout_functions.ts, as well as globally in dinou.config.ts.
true): Unless overridden in the segment or in dinou.config.ts, any valid dynamic path not pre-generated at build time is generated on-demand and cached statically (ISG).dinou.config.ts): Setting allowISG: false inside defineConfig({ allowISG: false }) switches the entire project to strict SSG-only mode by default, while allowing individual dynamic segments to explicitly opt in with export const allowISG = true.false): Returning false disables on-demand generation for that segment's dynamic parameters. Any unlisted parameter returns 404 Not Found immediately.() => boolean | Promise<boolean> lets you dynamically evaluate feature flags, environment stages, or upstream load before permitting on-demand generation.dinou.config.ts allowISG | Segment allowISG (page_functions / layout_functions) | Effective allowISG |
|---|---|---|
omitted (or true) | omitted | true (on-demand ISG enabled by default) |
omitted (or true) | false | false (segment opts out of ISG; build-time paths only) |
| false | omitted | false (strict SSG-only by default across the project) |
| false | true | true (segment explicitly opts into on-demand ISG) |
// src/blog/[slug]/page_functions.ts
import type { PageFunctions } from "dinou";
export const getStaticPaths: PageFunctions<"/blog/[slug]">["getStaticPaths"] = [
"hello-world",
"dinou-9-4",
];
// Strictly serve build-time pre-rendered paths; any other slug returns 404
export const allowISG: PageFunctions["allowISG"] = false;// 1. dinou.config.ts — Disable on-demand ISG project-wide by default
import { defineConfig } from "dinou";
export default defineConfig({
allowISG: false,
});
// 2. src/products/[id]/page_functions.ts — Explicitly opt in for long-tail products
import type { PageFunctions } from "dinou";
export const allowISG: PageFunctions["allowISG"] = true;// src/blog/[slug]/page_functions.ts
import type { PageFunctions } from "dinou";
import { getFeatureFlag } from "@/lib/flags";
// Protect origin database during maintenance or traffic spikes
export const allowISG: PageFunctions["allowISG"] = async () => {
const isgAllowed = await getFeatureFlag("allow_ondemand_rendering");
return isgAllowed;
};// 1. Parent Layout: src/team/[team]/layout_functions.ts
import type { LayoutFunctions } from "dinou";
export const getStaticPaths: LayoutFunctions<"/team/[team]">["getStaticPaths"] = ["alpha"];
export const allowISG: LayoutFunctions["allowISG"] = false; // Only "alpha" is valid
// 2. Child Page: src/team/[team]/posts/[postId]/page_functions.ts
import type { PageFunctions } from "dinou";
export const getStaticPaths: PageFunctions<"/team/[team]/posts/[postId]">["getStaticPaths"] = [
{ team: "alpha", postId: "post-1" },
];
export const allowISG: PageFunctions["allowISG"] = true; // New posts under "alpha" can use ISG!In Dinou, allowISG (just like validateParams) is evaluated independently per segment along the active layout chain rather than overwriting a single route-wide boolean:
Each layout validates only the dynamic URL parameters accumulated up to its own directory. When a parent dynamic layout's parameter is valid, it never overwrites a child dynamic page's allowISG = true.
If a parent layout has no dynamic parameters of its own (e.g. src/blog/layout_functions.ts), setting allowISG = false on that layout is a safe no-op and never blocks dynamic child pages (src/blog/[slug]).
Checks run strictly along the active layout chain. Any ancestor layout bypassed via no_layout or reset_layout will never block its child routes.
When any active layout or page rejects a parameter via allowISG = false or validateParams, Dinou returns 404 Not Found consistently on both direct URL loads and client-side navigations.
/team/[team]/posts/[postId] (assuming team = "alpha" and postId = "post-1" were pre-rendered at build time)Layout /team/[team] | Page posts/[postId] | Request URL | Result |
|---|---|---|---|
| allowISG: false | allowISG: true | /team/alpha/posts/post-1 | 200 OK — Served directly from build-time static cache. |
| allowISG: false | allowISG: true | /team/alpha/posts/post-2 | 200 OK — team = "alpha" passes layout check; new post-2 is generated and cached via ISG. |
| allowISG: false | allowISG: true | /team/beta/posts/post-1 | 404 Not Found — team = "beta" is rejected by layout allowISG = false. |
| allowISG: true | allowISG: false | /team/beta/posts/post-1 | 404 Not Found — team = "beta" is allowed by layout, but /team/beta/posts/post-1 was not pre-rendered for the page. |
| allowISG: true | allowISG: true | /team/beta/posts/post-1 | 200 OK — Both team = "beta" and /team/beta/posts/post-1 are generated and cached on-demand via ISG. |
revalidate (ISR & Dynamic SSR Escape)The revalidate export is Dinou's single source of truth for segment caching and rendering behavior in both page_functions.ts and layout_functions.ts (where layouts and child pages maintain independent cache timers). It is measured in seconds (s).
Dynamic SSR: Escapes static generation (which is the default). The page is rendered dynamically on every incoming request with live database reads.
Incremental Static Regeneration (ISR): The pre-rendered HTML/RSC payload is served from static cache and re-evaluated in the background at most once every N seconds (stale-while-revalidate).
Pure Static (SSG): Pre-rendered at build time and cached indefinitely until explicit on-demand invalidation via revalidatePage(), revalidateLayout(), revalidatePath(), or revalidateTag().
Type-Safe Examples: Constant or Function Declaration
// src/posts/[id]/page_functions.ts
import type { PageFunctions } from "dinou";
import { getArticleStatus } from "@/lib/articles";
// 1. Force Dynamic SSR on every request (< 1 or 0, replaces legacy 'dynamic' export)
export const revalidate: PageFunctions["revalidate"] = 0;
// 2. Incremental Static Regeneration (re-evaluates every 60 seconds)
// export const revalidate: PageFunctions["revalidate"] = 60;
// 3. Pure Static (SSG): Cached indefinitely until on-demand invalidation
// export const revalidate: PageFunctions["revalidate"] = false;
// 4. Type-safe async function: adjust TTL dynamically based on content volatility
// export const revalidate: PageFunctions["revalidate"] = async () => {
// const status = await getArticleStatus();
// return status.isBreakingNews ? 15 : 3600; // 15s for breaking news, 1h for standard stories
// };export function dynamic(). In Dinou, dynamic has been completely removed. Setting export const revalidate: PageFunctions["revalidate"] = 0; (or any value < 1) is the official, unified way to escape static generation.getCacheTags (Cache Tagging)Assigns custom invalidation tags to a cached page_functions.ts or layout_functions.ts segment (receiving the dynamic parameters accumulated up to that segment), allowing individual pages or layouts to be surgically purged and regenerated on-demand using revalidateTag(tag) (On-Demand Revalidation).
export const getCacheTags = ["catalog"];`product-${params?.id}`).// src/products/[id]/page_functions.ts
import type { PageFunctions } from "dinou";
// Best Practice: Type-safe synchronous cache tags
export const getCacheTags: PageFunctions<"/products/[id]">["getCacheTags"] = (params) => {
// Associate the generated page with a general tag and a product tag
return [
"products",
`product-${params?.id}`
];
};// src/products/[id]/page_functions.ts
import type { PageFunctions } from "dinou";
import { db } from "@/lib/db";
// Best Practice: Type-safe async tag resolver
export const getCacheTags: PageFunctions<"/products/[id]">["getCacheTags"] = async (params) => {
// Query product relationships to attach category and brand tags not present in URL
const product = await db.products.findById(params?.id);
return [
"products",
`product-${params?.id}`,
`category-${product.categorySlug}`,
`brand-${product.brandSlug}`,
];
};ppr (Partial Prerendering)Partial Prerendering (PPR) combines the instant TTFB (Time to First Byte) of a static page with the real-time capabilities of dynamic server-side rendering over a single HTTP response. It can be configured per segment in page_functions.ts and layout_functions.ts, or globally in dinou.config.ts.
PPR eliminates the traditional trade-off between static and dynamic rendering by dividing delivery into two phases over a single HTTP connection:
All static UI (layouts, headers, navigation) along with the skeleton placeholders defined in <Suspense fallback={...}> are pre-rendered at build time and delivered immediately with zero server wait time.
Inside <Suspense>, async Server Components, Server Components (sync or async) reading cookies, headers, query, or useSearchParams(), and Client Components receiving un-awaited Promise props stream concurrently at request time, replacing each fallback skeleton in-place as data resolves. (To resolve a build-time async Server Component directly into the Static Shell instead of opening a dynamic hole, call noDynamic() from "dinou" synchronously before its first await.)
false): Every layout and page defaults to ppr = false unless explicitly enabled in its own configuration file or globally in dinou.config.ts.dinou.config.ts): Setting defineConfig({ ppr: true }) enables PPR across all layouts and pages by default, while allowing individual segments to opt out with export const ppr = false.layout, nested layout, or page) resolves ppr strictly from its own layout_functions.ts or page_functions.ts, falling back directly to dinou.config.ts. Enabling ppr = true on a parent layout never cascades automatically to child layouts or pages.() => boolean | Promise<boolean> to evaluate environment variables or remote feature flags.dinou.config.ts ppr | Segment ppr (page_functions / layout_functions) | Effective ppr for That Segment |
|---|---|---|
omitted (or false) | omitted | false (standard SSG / ISR / Dynamic SSR by default) |
omitted (or false) | true | true (PPR enabled exclusively for that segment) |
| true | omitted | true (PPR enabled by default across all segments) |
| true | false | false (segment explicitly opts out of PPR) |
// src/dashboard/page_functions.ts
import type { PageFunctions } from "dinou";
import { getFeatureFlag } from "@/lib/flags";
// 1. Static Boolean (Standard): Enable PPR for this page segment
export const ppr: PageFunctions["ppr"] = true;
// 2. Dynamic Async Function: Evaluate remote rollout flags or A/B testing
// export const ppr: PageFunctions["ppr"] = async () => {
// const isPPREnabled = await getFeatureFlag("enable_ppr_dashboard");
// return isPPREnabled;
// };// 1. dinou.config.ts — Enable PPR globally across all layouts and pages
import { defineConfig } from "dinou";
export default defineConfig({
ppr: true,
});
// 2. src/about/page_functions.ts — Opt out on a purely static page
import type { PageFunctions } from "dinou";
export const ppr: PageFunctions["ppr"] = false;// 1. Parent Layout: src/dashboard/layout_functions.ts
import type { LayoutFunctions } from "dinou";
// Enables PPR ONLY for src/dashboard/layout.tsx (and its parallel @slots).
// Child layouts and pages do NOT inherit this automatically!
export const ppr: LayoutFunctions["ppr"] = true;
// 2. Child Page: src/dashboard/page_functions.ts
import type { PageFunctions } from "dinou";
// If dinou.config.ts omits ppr, this page would default to ppr = false
// unless it explicitly opts in as well:
export const ppr: PageFunctions["ppr"] = true;Because layouts and pages are independent segments, Dinou evaluates each segment inside its own isolated PPR execution scope without bleeding across boundaries:
Defining ppr = true in src/dashboard/layout_functions.ts applies exclusively to src/dashboard/layout.tsx and its parallel @slots. Child layouts and child pages resolve their own ppr setting independently.
On mixed routes (e.g. a ppr = true layout wrapping a ppr = false page), <Suspense> boundaries inside the ppr = false segment resolve statically at build time instead of deferring to runtime streaming.
Reading req.cookies, req.headers, req.query, calling useSearchParams() in a Server Component, or rendering <DinouCacheSlot revalidate={0}> inside a "ppr: false" segment (even inside <Suspense>)—or outside <Suspense> in a "ppr: true" segment—triggers a Dynamic SSR bailout to protect cache integrity.
During client-side page navigations, Dinou renders only the target page segment in isolation without re-evaluating ancestor layouts or their @slots on the server.
Layout ppr | Page ppr | Route Rendering Behavior |
|---|---|---|
| false | false | Standard SSG / ISR (or Dynamic SSR if a dynamic request API is read). |
| true | false | Composite PPR: The layout streams its <Suspense> boundaries at request time, while the page is statically pre-rendered inside the instant shell. |
| false | true | Composite PPR: The layout is statically pre-rendered in the shell, while the page streams its <Suspense> boundaries at request time. |
| true | true | Full PPR: Both layout and page deliver their static shells immediately (0ms TTFB) and stream their respective <Suspense> boundaries in parallel. |
export default)You can declare and export a single consolidated configuration object via export default pageConfig in page_functions.ts (or export default layoutConfig in layout_functions.ts).
Both models—traditional named exports (export const revalidate = ...) and the consolidated default export—are fully interchangeable, can be mixed across routes, and even combined in the same file.
Modern Pattern: Consolidated page_functions.ts
// src/blog/[slug]/page_functions.ts
import type { PageFunctions } from "./dinou";
interface BlogProps {
post: { title: string; content: string };
}
// "./dinou" pre-binds { slug: string } automatically
// (or import PageFunctions from "dinou" and write PageFunctions<"/blog/[slug]", BlogProps>)
const pageConfig: PageFunctions<BlogProps> = {
ppr: true,
revalidate: 60,
allowISG: true,
getStaticPaths: ["getting-started", "page-functions"],
validateParams: (params) => Boolean(params?.slug),
getCacheTags: (params) => ["blog", `post-${params?.slug}`],
getProps: async (params) => {
const post = await fetchPost(params?.slug ?? "");
return { post };
},
};
export default pageConfig;Consolidating route lifecycles into a single typed object offers major ergonomics improvements over declaring multiple separate exports:
Typing the object once with PageFunctions<"/blog/[slug]", BlogProps> automatically propagates parameter types to getProps(params), validateParams(params), and getCacheTags(params), while validating that getProps returns BlogProps. There is zero need to import RouteParams or repeat signatures across separate functions.
Pressing Ctrl + Space inside the config object instantly reveals every supported Dinou contract (ppr, revalidate, allowISG, getStaticPaths, validateParams, getCacheTags, getProps). This prevents typos and catches unrecognized options at compile-time.
Because pageConfig is a plain JavaScript object, you can compose reusable higher-order functions to apply shared caching, security, or telemetry policies across multiple routes:
// src/utils/route-helpers.ts (shared helper: import from "dinou")
import type { DinouRoutePattern, PageFunctions } from "dinou";
// Reusable higher-order wrapper with optional default generics
export function withProtectedCache<
TRouteOrParams extends DinouRoutePattern | object = any,
TProps = any
>(
config: PageFunctions<TRouteOrParams, TProps>
): PageFunctions<TRouteOrParams, TProps> {
return {
...config,
revalidate: 120,
getCacheTags: async (params) => [
"tenant-global",
...(typeof config.getCacheTags === "function"
? await config.getCacheTags(params)
: config.getCacheTags ?? []),
],
};
}// src/dashboard/page_functions.ts
import { withProtectedCache } from "@/utils/route-helpers";
interface DashboardProps {
stats: { usersCount: number; activeSessions: number };
}
// Pass explicit generics for strict validation, or omit them for auto-inference
export default withProtectedCache<"/dashboard", DashboardProps>({
getProps: async () => {
const stats = await fetchStats();
return { stats }; // Validated strictly against DashboardProps
},
});You do not need to choose exclusively between named exports and export default. Both can coexist seamlessly in the same file.
revalidate, ppr, getProps, validateParams, allowISG, getStaticPaths, getCacheTags), Dinou first looks for an explicit named export on the module. If absent, it falls back to the corresponding property on export default.Pattern: Shared Base Preset with Granular Override
This resolution rule enables a powerful architectural pattern: you can export a shared base preset across multiple routes, and use a named export only when a specific page needs to deviate from the default policy (such as opting out of caching for real-time SSR):
// src/blog/[slug]/page_functions.ts
import baseBlogConfig from "@/config/base-blog.config";
// 1. Export the shared preset (getProps, validateParams, getStaticPaths, cache tags)
export default baseBlogConfig;
// 2. Granular override: While baseBlogConfig specifies revalidate = 3600 (ISR),
// this specific breaking-news page requires real-time SSR:
export const revalidate = 0;Inside a route directory, importing PageFunctions<TProps> from "./dinou" pre-binds that folder's RouteParams automatically. When importing from "dinou", the signature is PageFunctions<TRouteOrParams = any, TProps = any>—and all type arguments remain optional:
1. Contextual Zero-Boilerplate (Recommended in Route Files): import type { PageFunctions } from "./dinou"
Pre-binds the current route directory's parameters automatically without repeating route string patterns:
// src/shop/[id]/page_functions.ts
import type { PageFunctions } from "./dinou";
interface ShopProps {
item: { id: string; name: string; price: number };
}
// RouteParams ({ id: string }) is pre-bound automatically!
const pageConfig: PageFunctions<ShopProps> = {
getProps: async (params) => {
const item = await fetchItem(params?.id ?? "");
return { item }; // Validated strictly against ShopProps
},
};
export default pageConfig;2. Zero Generics: PageFunctions
When the route only defines segment-level directives without dynamic parameter validation or getProps:
import type { PageFunctions } from "dinou";
// No generics required
const pageConfig: PageFunctions = {
ppr: true,
revalidate: 86400, // 24h ISR cache
};
export default pageConfig;3. Explicit Route Pattern Only: PageFunctions<TRoute>
When importing from "dinou" with dynamic parameters used in validateParams, getCacheTags, or getStaticPaths, while data fetching lives directly inside the page.tsx Server Component:
import type { PageFunctions } from "dinou";
// Route string infers { section: string; slug: string }
const pageConfig: PageFunctions<"/docs/[section]/[slug]"> = {
revalidate: 3600,
validateParams: (params) => params?.section === "guides",
getCacheTags: (params) => ["docs", `section-${params?.section}`],
getStaticPaths: [
{ section: "guides", slug: "get-started" },
{ section: "guides", slug: "installation" },
],
};
export default pageConfig;4. Explicit Route & Props Generics: PageFunctions<TRoute, TProps>
When importing from "dinou" and validating both explicit route parameters and returned props:
import type { PageFunctions } from "dinou";
interface ShopProps {
item: { id: string; name: string; price: number };
}
const pageConfig: PageFunctions<"/shop/[id]", ShopProps> = {
getProps: async (params) => {
const item = await fetchItem(params?.id ?? "");
return { item }; // Strictly validated against ShopProps
},
};
export default pageConfig;layout_functions.tsAll features, type inference rules, composition patterns, and precedence behaviors apply identically to layouts using LayoutFunctions (including intermediate layouts without a sibling page.tsx) and export default layoutConfig:
// src/workspace/[org]/layout_functions.ts
import type { LayoutFunctions } from "./dinou";
import { db } from "@/lib/db";
interface WorkspaceLayoutProps {
workspace: { name: string; plan: string };
}
// "./dinou" pre-binds { org: string } automatically for this layout directory
// (or import LayoutFunctions from "dinou" and write LayoutFunctions<"/workspace/[org]", WorkspaceLayoutProps>)
const layoutConfig: LayoutFunctions<WorkspaceLayoutProps> = {
ppr: true, // Enables PPR for this layout shell (without cascading to child pages)
revalidate: 3600, // Cache layout static shell independently for 1 hour
validateParams: (params) => Boolean(params?.org && /^[a-z0-9-]+$/.test(params.org)),
getCacheTags: (params) => ["workspaces", `workspace-${params?.org}`],
getProps: async (params) => {
const workspace = await db.workspaces.findBySlug(params?.org ?? "");
return { workspace };
},
};
export default layoutConfig;A complete, end-to-end example demonstrating how page and layout configurations seamlessly connect server lifecycles with their corresponding React components using zero-boilerplate contextual types from "./dinou":
// src/blog/[slug]/page_functions.ts
import type { PageFunctions } from "./dinou";
import { db } from "@/lib/db";
// 1. Define page props types
export interface BlogPost {
title: string;
slug: string;
content: string;
author: string;
publishedAt: string;
}
export interface BlogPageProps {
post: BlogPost;
}
// 2. Consolidated, strongly-typed page configuration
// ("./dinou" pre-binds { slug: string } automatically)
const pageConfig: PageFunctions<BlogPageProps> = {
// Caching Strategy & PPR configuration
revalidate: 60, // ISR 60s
ppr: true, // PPR: Static shell + Suspense streaming
// Static Paths for pre-rendering at build time
getStaticPaths: [
"getting-started",
"building-with-dinou",
],
// Parameter validation hook (returns false to abort with 404)
validateParams: (params) => {
return typeof params?.slug === "string" && params.slug.length >= 3;
},
// Cache tags for on-demand revalidation via revalidateTag("blog")
getCacheTags: (params) => {
return ["blog", `post-${params?.slug}`];
},
// Props loader: loads article data for the 0ms static shell
getProps: async (params) => {
// params?.slug is automatically inferred as string | undefined
const post = await db.posts.findUnique({ where: { slug: params?.slug } });
if (!post) throw new Error("Post not found");
// Strictly validated against BlogPageProps
return { post };
},
};
export default pageConfig;// src/blog/[slug]/page.tsx
import { Suspense } from "react";
import type { PageProps } from "./dinou";
import type { BlogPageProps } from "./page_functions";
import { RealtimeViews, ViewsSkeleton } from "./components";
// PageProps<BlogPageProps> combines pre-bound { params: { slug: string } } with BlogPageProps
export default function BlogPostPage({ params, post }: PageProps<BlogPageProps>) {
return (
<article className="max-w-2xl mx-auto py-8">
{/* 1. Static shell (pre-rendered at build time, delivered with 0ms TTFB) */}
<span className="text-xs text-muted-foreground font-mono">/blog/{params.slug}</span>
<h1 className="text-3xl font-bold">{post.title}</h1>
<div className="text-sm text-muted-foreground my-2">
By {post.author} • published {post.publishedAt}
</div>
<div className="prose mt-6">{post.content}</div>
{/* 2. PPR Dynamic Stream: Real-time analytics streamed in via Suspense */}
<Suspense fallback={<ViewsSkeleton />}>
<RealtimeViews slug={params.slug} />
</Suspense>
</article>
);
}// src/blog/layout_functions.ts
import type { LayoutFunctions } from "./dinou";
import { db } from "@/lib/db";
// 1. Define layout data contract
export interface BlogCategory {
id: string;
name: string;
count: number;
}
export interface BlogLayoutData {
categories: BlogCategory[];
featuredSlug: string;
}
// 2. Consolidated, strongly-typed layout configuration
const layoutConfig: LayoutFunctions<BlogLayoutData> = {
// Segment-level caching strategy for the layout shell
revalidate: 300, // Layout revalidates every 5 mins
ppr: true,
// Dedicated layout loader typed via LayoutFunctions
getProps: async () => {
const categories = await db.categories.findMany();
const featured = await db.posts.findFirst({ where: { featured: true } });
// Injected directly as props into layout.tsx
return {
categories,
featuredSlug: featured?.slug ?? "welcome",
};
},
};
export default layoutConfig;// src/blog/layout.tsx
import type { LayoutProps } from "./dinou";
import type { BlogLayoutData } from "./layout_functions";
// LayoutProps<BlogLayoutData> injects children, params, @slots, and BlogLayoutData
export default function BlogLayout({
children,
categories,
featuredSlug,
}: LayoutProps<BlogLayoutData>) {
return (
<div className="blog-container">
<aside className="blog-sidebar">
<h3>Categories</h3>
<ul>
{categories.map((c) => (
<li key={c.id}>{c.name} ({c.count})</li>
))}
</ul>
</aside>
<main className="blog-content">
{children}
</main>
</div>
);
}