Master Dinou's navigation system: smooth SPA soft transitions, automatic hover prefetching, universal URL hooks (usePathname & useSearchParams), universal redirect(), the Client Router Cache lifecycle with fresh, imperative useRouter controls, and Directory-First relative routing.
Dinou generates automatic route types and contextual "./dinou" helpers so <Link> and router.push() provide zero-runtime autocomplete and compile-time error checking.
In Dinou, navigating between routes does not trigger a full browser refresh. Instead, Dinou operates as a high-performance single-page application (SPA):
The primary way to navigate between pages is the <Link> component imported from "dinou" (or from contextual "./dinou" inside route folders when using relative links). It intercepts standard left-clicks, preserves modifier clicks (Cmd/Ctrl/Shift/Alt) and middle/right clicks, respects target (e.g. target="_blank") and download, skips external URLs and local #hash anchors, and prefetches internal routes on hover:
// src/components/navigation-bar.tsx
import { Link } from "dinou";
export function NavigationBar({ post }: { post: { slug: string } }) {
return (
<nav className="flex gap-4">
{/* ✅ Type-Safe absolute href (or use the equivalent `to` prop alias) */}
<Link href="/dashboard">Dashboard</Link>
{/* ✅ Dynamic route pattern (Ctrl + Space autocompleted) with typed params */}
<Link href="/blog/[slug]" params={{ slug: post.slug }}>
Post
</Link>
{/* ✅ Or direct template string interpolation (without params) */}
<Link href={`/blog/${post.slug}`}>Post (Template)</Link>
{/* Disable hover prefetch for heavy routes or rarely visited pages */}
<Link href="/analytics" prefetch={false}>
Analytics
</Link>
{/* ❌ TypeScript compile error on invalid/dead links */}
{/* <Link href="/broken-link">Broken</Link> */}
</nav>
);
}Prop note: <Link> accepts both href and to interchangeably (alongside all standard HTML <a> attributes), plus params, from, prefetch (defaults to true), and fresh (defaults to false).
<a> tags also trigger client-side soft navigation via global click delegation in Dinou (while respecting target, download, modifier keys, non-left clicks, and external URLs). However, they do not provide compile-time route validation, hover prefetching, parameter interpolation, or the fresh prop offered by <Link>.To navigate imperatively from event handlers, timers, or form submissions, use the useRouter() hook inside Client Components ("use client"):
// src/components/login-button.tsx
"use client";
import { useRouter } from "dinou";
export default function LoginButton() {
const router = useRouter();
const handleLogin = async () => {
await loginUser();
// Navigate programmatically
router.push("/dashboard");
// Or force fresh server data after a mutation:
// router.push("/dashboard", { fresh: true });
};
return <button onClick={handleLogin}>Log In</button>;
}| Method | Behavior & Description |
|---|---|
| router.push(href, options?) | Navigates to the target route and pushes a new entry onto the browser history stack. Supports { fresh: true }, { params } for dynamic patterns (e.g. "/blog/[slug]"), { from } for relative paths, #hash scrolling, and external URLs (falling back cleanly to window.location.assign()). |
| router.replace(href, options?) | Navigates to the route, replacing the current history entry without pushing a new state. Supports { fresh: true }, { params }, { from }, #hash fragments, and external URLs (via window.location.replace()). |
| router.back() | Navigates back to the previous page in history (equivalent to clicking the browser Back button). |
| router.forward() | Navigates forward to the next page in the history stack. |
| router.refresh(options?) | Soft Reload: Evicts pageCache for the current route and re-fetches server components without losing client React state or scroll position. Pass { layout: true } to also purge layoutCache and re-render the active layout shell. |
| router.refreshSlot(slotId, options?) | Re-fetches and updates matching <DinouCacheSlot> boundaries (by id, tag, or "*" wildcard) without re-rendering the surrounding page, returning a Promise<void> that resolves once settled. Pass { fresh: true } to bypass server-side slot cache. Also exported standalone as refreshSlot(slotId, options?). |
Referential Stability: The object returned by useRouter() (both from "dinou" and contextual "./dinou") is memoized against router context, making it safe to include in useEffect or useCallback dependency arrays without triggering re-render loops.
Dinou provides two universal URL hooks exported from "dinou" that work seamlessly in both Server Components (reading from the active AsyncLocalStorage request context during SSR) and Client Components (subscribing to RouterContext and re-rendering automatically on soft navigation):
"/docs/navigation") stripped of query strings, hashes, and trailing slashes. Ideal for highlighting active navigation links.URLSearchParams instance for the current query string. Calling it in a Server Component triggers dynamic SSR bailout (or registers a Dynamic PPR Hole when wrapped in <Suspense> on a ppr = true route), while calling it in a Client Component preserves SSG, ISR, PPR, and export-static (hydrating with an empty URLSearchParams first before syncing live query params with zero hydration mismatch).See full Server & Client signatures in API Reference: usePathname() and useSearchParams(). For cookies, HTTP headers, response mutations, or server env bindings, see Request Context (getContext).
// src/components/filter-tabs.tsx
"use client";
import { Link, usePathname, useSearchParams } from "dinou";
export function FilterTabs() {
const pathname = usePathname();
const searchParams = useSearchParams();
const activeSort = searchParams.get("sort") ?? "latest";
return (
<div className="flex items-center gap-3">
<span className="text-xs text-muted-foreground">Path: {pathname}</span>
<Link
href="?sort=latest"
className={activeSort === "latest" ? "font-bold underline" : ""}
>
Latest
</Link>
<Link
href="?sort=popular"
className={activeSort === "popular" ? "font-bold underline" : ""}
>
Popular
</Link>
</div>
);
}To redirect declaratively from a Server Component or Client Component, use redirect(destination) from "dinou". Unlike frameworks where redirect() throws an internal exception, in Dinou redirect() returns a ReactNode—always return its result:
// src/dashboard/page.tsx
import { getContext, redirect } from "dinou";
export default async function DashboardPage() {
const ctx = getContext();
const sessionToken = ctx.req.cookies.session;
if (!sessionToken) {
// ✅ Always use `return redirect(...)`
return redirect("/login");
}
const profile = await fetchUserProfile(sessionToken);
return <h1>Welcome back, {profile.name}</h1>;
}Before headers are sent (Server): redirect("/login") issues a native HTTP 302 redirect on initial document requests (optimal for SEO and zero-flash redirects) or sets x-rsc-redirect during soft RSC navigation. Calling redirect() inside page_functions.ts or layout_functions.ts (getProps) immediately short-circuits rendering before any JSX executes.
After streaming starts or on the Client: If React has already flushed headers inside a streamed <Suspense> boundary—or if called on the client—Dinou automatically renders <ClientRedirect to="/login" /> to replace the route seamlessly in the browser.
To deliver instant page transitions without unnecessary server requests, Dinou features an in-memory Client Router Cache. Understanding how this cache operates is key to knowing when and why to use the fresh prop.
During client execution, Dinou maintains three dedicated in-memory caches in the browser tab:
pathname + search (with any #hash fragment stripped cleanly from cache keys and wire fetches).layoutKey + search). Navigating between child pages within the same layout never re-fetches the layout unless router.refresh({ layout: true }) is called.popstate).<Link href="/pricing">, Dinou prefetches any uncached target layout into layoutCache and stores the streaming page RSC promise directly into pageCache."/pricing". Because the payload was already prefetched into pageCache, the transition renders instantly with 0ms network latency.popstate events read from pageCache and restore the previous scroll position from scrollCache without making network requests.While caching provides instantaneous navigation, pages with volatile data or pages visited immediately after a mutation (e.g., checkout, profile updates, or inventory counters) need fresh server state. The fresh prop provides explicit, deterministic cache busting:
Hovering over a <Link fresh> does not prefetch potentially stale data before the user actually clicks.
On navigation, the router runs pageCache.delete(finalPath) and increments a monotonic version counter (____v____) so in-flight prefetches never overwrite fresh state.
Issues a live fetch(..., { cache: "no-store" }) RSC request to the server, bypassing browser HTTP caches and re-executing server components.
// Ideal for live feeds, stock tickers, or carts
<Link href="/live-feed" fresh>
Live Feed
</Link>// Navigate after a mutation to force fresh server data
const handleUpdate = async () => {
await updateProfile(data);
router.push("/profile", { fresh: true });
};| Mechanism / Scope | Cache Behavior | Network Request | Typical Use Case |
|---|---|---|---|
| Standard <Link> | Uses pageCache & layoutCache if prefetched or visited | 0ms if in cache; single request on first visit | General navigation, blogs, docs, marketing pages |
| <Link fresh> / { fresh: true } | Purges pageCache.delete(url) + version bump | Always fetches live no-store RSC payload | Post-mutation redirects, active carts, volatile feeds |
| router.refresh(options?) | Purges pageCache (and layoutCache when { layout: true }) | Re-fetches current route (and optional layout) in-place | Polling, server function updates, header/session refresh |
| Hard Reload (F5) | Destroys all memory (all caches lost) | Full HTML document download + re-hydration | Emergency fallback; loses all client state |
In Dinou, all client-side navigations execute concurrently inside React 19's startTransition. This ensures that the current view remains fully interactive and visible while the target page's Server Components stream in from the server.
To inform users that a transition is occurring behind the scenes, Dinou provides the useNavigationLoading() hook:
Returns true while a route payload is actively streaming or preparing in the background, and resets to false the moment React 19 commits the new page tree.
Evaluates to false during server-side rendering (SSR), preventing hydration mismatches and flickering when the document first mounts.
Mount a client loading indicator in your root layout to provide visual feedback (similar to GitHub or YouTube) whenever a route transition is pending:
"use client";
import { useNavigationLoading } from "dinou";
export function NavigationProgressBar() {
const isNavigating = useNavigationLoading();
if (!isNavigating) return null;
return (
<div
role="progressbar"
aria-label="Page loading"
className="fixed top-0 left-0 right-0 z-50 h-1 bg-blue-500/20 overflow-hidden pointer-events-none"
>
<div className="h-full bg-blue-600 dark:bg-blue-400 animate-pulse w-full transition-all duration-300" />
</div>
);
}Because prefetched links resolve instantly in 0ms directly from pageCache, this progress bar only surfaces on fresh fetches (such as navigation with fresh: true or un-prefetched dynamic routes), keeping transitions ultra snappy.
Dinou resolves relative navigation paths (such as about, ./about, or ../dashboard) using a Directory-First Convention. This provides intuitive navigation that accurately mirrors your file system.
In a standard web browser, a URL like /blog/hello (without a trailing slash) treats hello as a file name, so a link to about resolves to /blog/about.
In Dinou, every route is treated as a directory because physically, each page is a folder containing a page.tsx component (e.g. src/blog/hello/page.tsx). Resolving relatively from a page navigates relative to that route's folder:
| Current Path | Relative Target | Resolved Path |
|---|---|---|
| /blog/hello | about | /blog/hello/about |
| /blog/hello | ./about | /blog/hello/about |
| /blog/hello | ../about | /blog/about |
This rule applies uniformly across all navigation methods, including <Link> (both href and to) and programmatic calls like router.push() and router.replace().
"./dinou" or Explicit fromInside any route folder, import { Link, useRouter } from "./dinou" to get automatic zero-boilerplate relative autocomplete and strict compile-time validation without writing from—or pass from explicitly when importing from global "dinou". Both bare child paths ("about") and dot-prefixed paths ("./about", "../about") autocomplete while typos like "./abouts" are rejected immediately: