Routing & Layouts
Master Dinou's file-system router: root and nested layouts, parallel slots with error isolation, route parameters, and layout control flags.
Looking for Type-Safe Routing?
Dinou provides zero-boilerplate contextual "./dinou" modules with auto-inferred PageProps, LayoutProps (including @slots), NotFoundProps, and compile-time validated <Link> navigation.
1. Overview & Directory Conventions
Every public route in Dinou maps directly to a folder inside src/ containing an entrypoint file (page.tsx, page.jsx, page.ts, or page.js). By default, pages are React Server Components (RSC) rendered natively on the server with zero client bundle overhead.
1.1. Core File Conventions
src/page.tsx → /src/blog/page.tsx → /blogsrc/blog/[slug]/page.tsx → /blog/hello-worldsrc/dashboard/settings/page.tsx → /dashboard/settings1.2. In-Memory Route Resolution
You never write central routing tables or configure URL maps manually. The folder structure inside src/ is your single source of truth.
When a request arrives (for example, /blog/hello-world), Dinou matches it entirely in memory:
- Instant matching: Directly locates
src/blog/[slug]/page.tsxin memory with zero subprocess overhead or disk I/O latency. - Parameter extraction: Automatically parses dynamic segments into typed
params(e.g.{ slug: "hello-world" }). - Layout nesting: Automatically wraps the page inside its parent layouts (
src/layout.tsx→src/blog/layout.tsx).
You can use .tsx, .ts, .jsx, or .js interchangeably across all pages and layouts.
2. Route Types & Pattern Matching
Dinou provides expressive pattern matching for static, dynamic, optional, and catch-all URL segments:
2.1. Static & Dynamic Segments
| Pattern | Folder Structure | URL Match Example | Parsed params |
|---|---|---|---|
| Static | src/about/page.tsx | /about | {} |
| Dynamic | src/blog/[slug]/page.tsx | /blog/hello | { slug: "hello" } |
| Optional Single | src/shop/[[category]]/page.tsx | /shop /shop/shoes | { category: undefined }{ category: "shoes" } |
2.2. Catch-All & Optional Catch-All
| Pattern | Folder Structure | URL Match Example | Parsed params |
|---|---|---|---|
| Catch-all (Required) | src/docs/[...slug]/page.tsx | /docs/routing/params | { slug: ["routing", "params"] } |
| Optional Catch-all | src/docs/[[...slug]]/page.tsx | /docs /docs/a/b | { slug: [] }{ slug: ["a", "b"] } |
Catch-all segments ([...slug]) consume all remaining path segments into a string array. Because they consume the remainder of the URL, Catch-all segments must always be the terminal (last) segment of a path definition.
2.3. The Strict No-Gap Rule
Dinou enforces a strict No-Gap Rule when resolving nested optional segments such as /inventory/[[warehouse]]/[[aisle]]:
You can omit optional segments only if they are omitted from the tail end of the URL:
/inventory/main ✅ (aisle omitted)
/inventory ✅ (both omitted)
You cannot omit an earlier optional parameter while setting a later one:
(Skip warehouse, set aisle: ambiguous URL structure)
2.4. Precedence & Deterministic Branch Backtracking
When multiple sibling folders could match a URL segment, Dinou evaluates candidates in a strict, deterministic specificity order:
Crucially, Dinou performs full multi-branch backtracking across route trees and (group) folders. For example, if both src/en/contact/page.tsx and src/[lang]/about/page.tsx exist, a request to /en/about checks the higher-priority static src/en/ branch first, sees no about child there, and cleanly backtracks to match src/[lang]/about/page.tsx with { lang: "en" } instead of returning a false 404.
3. Route Parameters & Validation
Dinou provides a clean, unified data contract. Route parameters are extracted from the URL and injected directly into components and server functions.
3.1. Dynamic Params Prop Injection
Every route and @slot directory can import zero-boilerplate segment types directly from its auto-generated contextual "./dinou" module (or import explicit pattern generics from "dinou"):
page.tsxcomponents:Page({ params }: PageProps)(orPageProps<{ post: Post }>with server props)layout.tsxcomponents:Layout({ params, children }: LayoutProps)(auto-includes sibling@slots)error.tsxboundaries:Error({ error, params }: ErrorProps)not_found.tsx404 boundaries:NotFound({ params }: NotFoundProps)- Parallel slot pages (
@slot/page.tsx):SlotPage({ params }: SlotProps) - Server data fetching:
getProps(params: RouteParams)(orPageFunctions/LayoutFunctions) inpage_functions.ts/layout_functions.ts
// src/blog/[slug]/page.tsx
import type { PageProps } from "./dinou";
interface PostData {
post?: { title: string; content: string };
}
export default function BlogPost({ params, post }: PageProps<PostData>) {
// ✅ params.slug is auto-inferred as string with zero route string literals!
return (
<article className="p-6">
<h1 className="text-2xl font-bold">{post?.title ?? params.slug}</h1>
<p className="mt-2 text-muted-foreground">{post?.content}</p>
</article>
);
}// src/blog/[slug]/page.tsx
import type { PageProps } from "dinou";
interface PostData {
post?: { title: string; content: string };
}
export default function BlogPost({
params,
post,
}: PageProps<"/blog/[slug]", PostData>) {
// ✅ Equivalent explicit route pattern generic from "dinou"
return (
<article className="p-6">
<h1 className="text-2xl font-bold">{post?.title ?? params.slug}</h1>
<p className="mt-2 text-muted-foreground">{post?.content}</p>
</article>
);
}Strict Signature Rule
page_functions.ts and layout_functions.ts, Dinou passes the parameters dictionary directly as the first argument: use getProps(params) and validateParams(params) (do not write getProps({ params })). However, in React components (page.tsx, layout.tsx, error.tsx, not_found.tsx, @slot/page.tsx), params is passed as a component prop: export default function Page({ params }).3.2. Route Validation (validateParams)
Exporting a validateParams(params) function from page_functions.ts or layout_functions.ts lets you enforce semantic validation rules in strict root-to-child order (ancestor layouts before child pages) before data fetching, rendering, or even serving cached HTML/RSC payloads. Returning false (or a Promise resolving to false) immediately vetoes the request and issues a clean 404 response:
// src/product/[id]/page_functions.ts
import type { RouteParams } from "./dinou";
export function validateParams(params: RouteParams) {
// Ensure the product ID is strictly numeric; otherwise render 404
return /^\d+$/.test(params.id);
}
export async function getProps(params: RouteParams) {
// Only called if validateParams returned true
const product = await db.products.findById(params.id);
return { product };
}- Dynamic SSR & SPA RSC Navigation: Returns an instant 404 on both hard HTML loads and client-side SPA fetches (
/____rsc_page____/*,/____rsc_layout____/*) without runninggetPropsor serving stale cached payloads. - Incremental Static Generation (ISG / ISR): Prevents invalid URLs from triggering on-demand page generation or polluting edge caches with broken pages. (To disable on-demand ISG entirely and serve only paths returned by
getStaticPaths, setallowISG = falsein the segment or globally indinou.config.ts—see Page & Layout Functions.) - Static Site Exports (SSG): Only valid parameter combinations generate HTML files during
dinou export-static.
3.3. Query Parameters Access
Query parameters (e.g. ?search=react&sort=asc) are deliberately isolated from static route matching to preserve edge cache stability. In Dinou, useSearchParams() is a universal hook that works seamlessly in both Server Components and Client Components:
Use useSearchParams() anywhere. It returns a standard Web URLSearchParams instance:
import { useSearchParams } from "./dinou";
// Works in Server Components & "use client" components!
export default function SearchPage() {
const searchParams = useSearchParams();
const q = searchParams.get("search") ?? "";
return <div>Search: {q}</div>;
}Outside React components (where hooks cannot run), access the active query synchronously via getContext().req.query:
import { getContext } from "dinou"; // also in "./dinou", "dinou/server", "dinou/config"
// src/search/page_functions.ts
// getContext() always returns RequestContextStore (never null/undefined)
export async function getProps() {
const ctx = getContext();
const search = ctx.req.query.search;
return { search };
}"use server"; // Declared at the top of the file
import { getContext } from "dinou";
// src/actions/items.ts
export async function filterItems() {
const ctx = getContext();
const search = ctx.req.query.search;
return db.items.find({ q: search });
}Static Optimization: Client vs. Server useSearchParams()
useSearchParams() inside a Server Component (or reading getContext().req.query on the server) opts that route into Dynamic SSR. Calling useSearchParams() inside a Client Component ("use client") preserves SSG, ISR, PPR, and dinou export-static without dynamic bailout—hydrating cleanly with an empty URLSearchParams first and immediately syncing live window.location.search on the client with zero hydration mismatch.4. Layouts & Special Files
Dinou provides special files that cascade down the directory hierarchy. They allow you to define the root document shell, compose nested layouts that preserve client state across navigations, isolate runtime errors, and break out of layout hierarchies using control flags.
4.1. Root Layout (src/layout.tsx)
The top-level src/layout.tsx file is the Root Layout of your application. It is responsible for rendering the outer HTML document shell (<html>, <head>, and <body>), importing global stylesheets or fonts, and wrapping all child routes and nested layouts (unless explicitly bypassed with reset_layout or no_layout, or partitioned into multiple root layouts via Route Groups):
// src/layout.tsx
import type { LayoutProps } from "./dinou";
import "./globals.css";
export default function RootLayout({ children }: LayoutProps) {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
<link rel="stylesheet" href="/styles.css" precedence="default" />
</head>
<body className="min-h-screen bg-background text-foreground antialiased">
{children}
</body>
</html>
);
}4.2. Nested Layouts (layout.tsx)
Placing a layout.tsx file inside any route directory (e.g. src/dashboard/[teamId]/layout.tsx) creates a nested layout that wraps all child pages and deeper sub-layouts in that subtree. Unlike the root layout, nested layouts do not include <html> or <body> tags—they mount directly inside their parent layout's {children} slot.
On client navigation between sibling pages, parent layouts preserve their React state, input fields, scroll position, and DOM tree without re-mounting. With LayoutProps from "./dinou", each layout automatically receives children, strongly typed cumulative params, auto-inferred sibling parallel slots (e.g. @sidebar → sidebar?: ReactNode), and any custom server props passed via LayoutProps<TProps> from an optional companion layout_functions.ts file:
// src/dashboard/[teamId]/layout.tsx
import type { LayoutProps } from "./dinou";
export default function DashboardLayout({
children,
params,
sidebar,
}: LayoutProps) {
// ✅ params.teamId (string) & sidebar?: ReactNode (@sidebar) are auto-inferred!
return (
<div className="flex min-h-screen">
<aside className="w-64 border-r p-4">{sidebar}</aside>
<main className="flex-1 p-6">
<h1 className="text-xl font-bold">Team: {params.teamId}</h1>
{children}
</main>
</div>
);
}Independent Layout Data Fetching & Caching (layout_functions.ts)
layout_functions.ts file for server data fetching (getProps), independent ISR lifetimes (revalidate), segment-isolated ppr, build-time path generation (getStaticPaths across [p], [[p]], [...s], [[...s]]), allowISG / validateParams guards, cache tags (getCacheTags), and O(1) surgical revalidation via revalidateLayout(). See Page & Layout Functions and 3D Segmentation (Horizontal Axis) for details.4.3. Layout Control Flags (reset_layout, no_layout)
Dinou allows you to break out of the nested layout hierarchy using empty flag files (files without extensions) placed in the route directory:
| Flag File | Applies To | Architectural Effect |
|---|---|---|
| reset_layout | layout.tsx | Resets the layout tree. This layout becomes the new root layout, completely ignoring all parent layouts (including src/layout.tsx). Perfect for marketing landing pages or auth portals. |
| no_layout | page.tsx not_found.tsx error.tsx | Bypasses all layouts entirely across the route. The page, custom 404, and error boundary render raw without any parent layout wrappers (ideal for embeddable widgets, checkout modals, or pure HTML canvas views). |
| no_layout_error | error.tsx | Granular override: prevents parent layouts from wrapping the error boundary UI only, while preserving layouts for the regular page. |
| no_layout_not_found | not_found.tsx | Granular override: prevents parent layouts from wrapping the custom 404 page only, while preserving layouts for the regular page. |
src/landing/reset_layout (empty file)
src/landing/page.tsx
→ The landing page ignores the root
src/layout.tsx header and navigation bar.4.4. Error Pages (error.tsx)
Create an error.tsx file in any route directory to catch and isolate runtime errors locally. If an exception occurs in a child component, Dinou bubbles up to the closest error.tsx, rendering it while keeping all parent layouts interactive:
// src/dashboard/[teamId]/error.tsx
import type { ErrorProps } from "./dinou";
// Auto-infers params.teamId and types the captured error (works in intermediate & @slot folders too)
export default function DashboardError({ error, params }: ErrorProps) {
return (
<div className="p-6 rounded-xl border border-rose-500/20 bg-rose-50/20">
<h3 className="text-rose-600 font-bold">Failed to load team {params.teamId}</h3>
<p className="text-xs text-muted-foreground mt-1">{error.message}</p>
{error.stack && (
<pre className="mt-3 p-3 bg-slate-900 text-slate-100 rounded text-xs overflow-auto">
{error.stack}
</pre>
)}
</div>
);
}// src/dashboard/[teamId]/error.tsx
import type { ErrorProps } from "dinou";
// Explicit segment pattern generic (supports page, intermediate, and @slot boundaries)
export default function DashboardError({
error,
params,
}: ErrorProps<"/dashboard/[teamId]">) {
return (
<div className="p-6 rounded-xl border border-rose-500/20 bg-rose-50/20">
<h3 className="text-rose-600 font-bold">Failed to load team {params.teamId}</h3>
<p className="text-xs text-muted-foreground mt-1">{error.message}</p>
{error.stack && (
<pre className="mt-3 p-3 bg-slate-900 text-slate-100 rounded text-xs overflow-auto">
{error.stack}
</pre>
)}
</div>
);
}// src/dashboard/[teamId]/error.tsx
import type { ErrorParams } from "dinou";
// Alternative: inline typing using the ErrorParams utility
export default function DashboardError({
error,
params,
}: {
error: Error;
params: ErrorParams<"/dashboard/[teamId]">;
}) {
return (
<div className="p-6 rounded-xl border border-rose-500/20 bg-rose-50/20">
<h3 className="text-rose-600 font-bold">Failed to load team {params.teamId}</h3>
<p className="text-xs text-muted-foreground mt-1">{error.message}</p>
{error.stack && (
<pre className="mt-3 p-3 bg-slate-900 text-slate-100 rounded text-xs overflow-auto">
{error.stack}
</pre>
)}
</div>
);
}Security Note: For production deployments, error.stack is automatically stripped by Dinou to prevent internal file paths and system details from leaking. In development mode, the full cleaned stack trace is provided.
4.5. Custom 404 Pages (not_found.tsx)
Define custom 404 views by placing not_found.tsx in any route or intermediate directory (with or without a sibling page.tsx). When an unmatched URL segment is requested or validateParams / allowISG: false rejects a request, Dinou bubbles up to render the closest not_found.tsx template inside its enclosing layout.
// src/blog/[slug]/not_found.tsx (Scoped to /blog/[slug])
import { Link, type NotFoundProps } from "./dinou";
// Automatically types params.slug as string
export default function NotFound({ params }: NotFoundProps) {
return (
<div className="flex flex-col items-center justify-center p-8 text-center">
<h2 className="text-3xl font-bold">404 - Article Not Found</h2>
<p className="mt-2 text-muted-foreground">
The article "{params.slug}" could not be located.
</p>
<Link
href="/"
className="mt-4 px-4 py-2 bg-primary text-primary-foreground rounded-lg font-medium text-sm"
>
Back to Home
</Link>
</div>
);
}// src/not_found.tsx (Global Root Fallback)
import { Link, type NotFoundProps } from "./dinou";
// Root NotFoundProps strictly ensures no dynamic params are accidentally accessed
export default function GlobalNotFound(_props: NotFoundProps) {
return (
<div className="flex flex-col items-center justify-center p-8 text-center">
<h2 className="text-3xl font-bold">404 - Page Not Found</h2>
<p className="mt-2 text-muted-foreground">
The requested page does not exist on this server.
</p>
<Link
href="/"
className="mt-4 px-4 py-2 bg-primary text-primary-foreground rounded-lg font-medium text-sm"
>
Back to Home
</Link>
</div>
);
}// 1. Sibling server contract: src/blog/[slug]/page_functions.ts
import type { RouteParams } from "./dinou";
export async function getProps(params: RouteParams) {
const suggestions = await db.posts.findMany({ take: 3 });
return { suggestions };
}
// 2. 404 Page: src/blog/[slug]/not_found.tsx
import { Link, type NotFoundProps } from "./dinou";
interface SuggestionsData {
suggestions: { id: string; title: string; slug: string }[];
}
export default function NotFound({
params,
suggestions,
}: NotFoundProps<SuggestionsData>) {
return (
<div className="flex flex-col items-center justify-center p-8 text-center">
<h2 className="text-3xl font-bold">404 - Article Not Found</h2>
<p className="mt-2 text-muted-foreground">
Could not find "{params.slug}". Here are some recommended articles:
</p>
{suggestions && (
<ul className="mt-4 space-y-1">
{suggestions.map((item) => (
<li key={item.id}>
<Link
href="/blog/[slug]"
params={{ slug: item.slug }}
className="text-primary hover:underline text-sm font-medium"
>
→ {item.title}
</Link>
</li>
))}
</ul>
)}
</div>
);
}Importing NotFoundProps from "./dinou" automatically binds the cumulative parameters for that directory (including intermediate folders without a sibling page.tsx). Alternatively, you can import NotFoundProps from "dinou" and pass the explicit pattern generic (e.g. NotFoundProps<"/blog/[slug]"> or NotFoundProps<"/">).
Can 404 Pages Receive Server Props via getProps?
Yes. If you define a page_functions.{ts,js,tsx,jsx,mjs} file in the same route directory as not_found.tsx, Dinou executes its getProps(params) server lifecycle and merges the returned data directly into the component's props alongside params (as demonstrated in the With Server Props tab above).
This allows 404 views to dynamically query databases or external APIs (such as recommended articles, related categories, or search fallbacks) and type them cleanly via NotFoundProps<SuggestionsData> from "./dinou" (or NotFoundProps<"/blog/[slug]", SuggestionsData> from "dinou").
Difference with error.tsx: While not_found.tsx can safely execute getProps, error.tsx pages never invoke server contracts (they receive strictly ErrorProps) to prevent compounding unhandled server exceptions.
5. Route Organization & Parallel Slots
Dinou provides dedicated directory conventions to organize enterprise codebases cleanly and compose parallel UI slots without impacting URL ergonomics:
5.1. Route Groups (folder)
Folders wrapped in parentheses (e.g. (auth), (marketing)) are omitted from the public URL path. They serve two fundamental architectural purposes in Dinou:
- Logical Organization: Group related routes together without introducing unwanted segment prefixes in the URL.
- Multiple Root Layouts: Apply completely different top-level layout wrappers to different areas of your application without URL changes.
In conventional file-system routers, a single global layout forces all pages to share the same top navigation bar and footer. With Dinou Route Groups, you can create independent root layouts for marketing pages versus authentication screens:
- •Independent Filesystem Paths:
src/(marketing)/layout.tsxandsrc/(auth)/layout.tsxlive in distinct disk directories, so there is zero file collision. - •Request to
/pricing: Dinou crawls into(marketing), matchespricing/page.tsx, and wraps it exclusively with the marketing layout. - •Request to
/login: Dinou crawls into(auth), matcheslogin/page.tsx, and wraps it exclusively with the auth layout.
src/layout.tsx, both groups nest inside it (e.g. for HTML <head> or global fonts). If omitted, each group acts as a completely separate root layout.Avoid URL Path Collisions
src/(marketing)/about/page.tsx and src/(auth)/about/page.tsx would cause a build/resolution collision because both map to /about.5.2. Escaping Route & Bundler Scanning with Underscore (_folder)
In Dinou, you do not need to prefix folders like components/, hooks/, actions/, or utils/ with an underscore. Any directory that simply does not contain a page.tsx (or page.jsx) is already completely ignored by the router and will never register a route.
The Real Purpose of "_": Parked, Draft & Legacy Code
_folderName) is to completely exclude that directory tree from both Dinou's router and Dinou's bundlers when parking legacy code, drafts, experiments, or archived routes that you want to keep in the repository without compiling or shipping them.How it Works in Practice:
Whenever Dinou encounters a folder starting with _, it completely bypasses that directory tree across RSC/SSR compilation, "use client" chunk generation, "use server" endpoint registration, and CSS/asset scanning. If a parked route folder uses contextual "./dinou" imports, Dinou still emits permissive fallback .d.ts shims in .dinou/routes/_... so those parked files remain error-free in your IDE—while excluding the parked routes from .dinou/types/routes.d.ts so any active <Link> pointing to them fails at compile time.
Coming from Next.js? Do Not Use _components or _actions for Active Code
_folder in Dinou is fully excluded from bundling—not just from URL routing. Active files cannot import modules from a _-prefixed directory (Dinou's bundler will immediately report an explicit compile-time error if attempted). Always name active colocated directories cleanly without a leading underscore, such as components/, hooks/, or actions/.5.3. Parallel Routes & Slots (@slot)
Parallel routes allow you to render multiple independent pages simultaneously inside the same parent layout (e.g., @sidebar, @analytics, @modal):
- src/dashboard/@sidebar/page.tsx
- src/dashboard/@analytics/page.tsx
- src/dashboard/page.tsx (main children)
- src/dashboard/layout.tsx
Slots are passed as named props alongside children and are automatically typed on LayoutProps:
// src/dashboard/layout.tsx
import type { LayoutProps } from "./dinou";
export default function Layout({
children,
sidebar,
analytics,
}: LayoutProps) {
// sidebar?: ReactNode & analytics?: ReactNode are auto-inferred!
return (
<div className="flex">
<aside>{sidebar}</aside>
<main>{children}</main>
<section>{analytics}</section>
</div>
);
}Parallel @slot directories can also live inside (group) folders and define nested sub-routes (e.g. src/dashboard/@analytics/settings/page.tsx matching /dashboard/settings). Inside any slot page, import SlotProps (or PageProps) from its own "./dinou" module to receive strongly typed cumulative route parameters.
5.4. Slot Error Containment Architecture
Dinou isolates errors within parallel slots to prevent a single widget failure from crashing the entire page:
error.tsx, Dinou safely falls back to rendering null for that slot without taking down the page.children page, and parent layouts remain fully mounted and interactive even if an individual slot fails to render.