Lesson 5 of 27Foundations
Layouts and Navigation
Build nested layouts that persist, navigate with Link and the router hooks, and redirect from server code.
A good app shell (sidebar, header, tabs) should not flicker, lose its scroll position, or reset a half-typed search box every time you click a link. In Next.js that comes from nested layouts and client-side navigation. Understanding exactly what re-renders on navigation is also how you debug "why did my state reset?" bugs.
Layouts wrap and persist
A layout is a component in a layout.tsx file that receives the page (or a nested layout) as children. Layouts nest by folder: app/layout.tsx wraps everything, app/dashboard/layout.tsx wraps every page under /dashboard.
import type { Metadata } from "next";
import "./globals.css";
export const metadata: Metadata = { title: "Acme" };
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}import { Sidebar } from "./_components/Sidebar";
export default function DashboardLayout({ children }: LayoutProps<"/dashboard">) {
return (
<div className="grid grid-cols-[240px_1fr]">
<Sidebar />
<main>{children}</main>
</div>
);
}The key property: on navigation, layouts that stay on screen are not re-rendered or remounted. Only the part of the tree below the deepest shared layout changes. Step through a navigation from /dashboard to /dashboard/settings:
Both layouts are shared by the old and new URL, so they stay mounted. The sidebar's search box keeps what you typed.
That is why layouts are the right home for navigation, sidebars and anything with state that should survive page changes. The flip side: a layout does not re-render when you move between its child pages, so it cannot show which child is active using its own props. Use usePathname() in a small Client Component for that (below).
Templates: when you want a reset
A template.tsx looks like a layout but gets a new key on each navigation, so everything inside it remounts: state resets and effects run again. Use it for things like a per-page enter animation or a form that must start empty on every page.
Try both in the preview. Type in each box, then switch pages.
Linking between pages
Use <Link> from next/link instead of a plain <a>:
import Link from "next/link";
import { getPosts } from "@/lib/posts";
export default async function BlogIndex() {
const posts = await getPosts();
return (
<ul>
{posts.map((post) => (
<li key={post.slug}>
<Link href={`/blog/${post.slug}`}>{post.title}</Link>
</li>
))}
</ul>
);
}<Link> gives you two things a plain anchor does not:
- Client-side transitions. Clicking does not reload the document. Next.js fetches the new route's server-rendered output (the RSC payload, a compact description of the rendered Server Components) and swaps in only the changed segments, keeping shared layouts and their state.
- Prefetching. In production, when a link scrolls into the viewport, Next.js loads the target route in the background. Static routes are prefetched fully; dynamic routes are prefetched down to their nearest
loading.tsx, so the loading state can show instantly on click.
You can tune this with the prefetch prop: leave it as the default, set prefetch={false} for long lists of rarely clicked links, or prefetch={true} to prefetch the full route.
Prefetching in detail, and useLinkStatus
Prefetching is the reason a well-built Next.js app feels instant, and it is also the reason some apps hammer their servers. You should know exactly what each setting does.
prefetch value | Static route | Dynamic route |
|---|---|---|
"auto" or null (the default) | Whole route and its data | Down to the nearest loading.tsx |
true | Whole route and its data | Whole route and its data |
false | Nothing, on viewport or on hover | Nothing, on viewport or on hover |
Three details catch people out:
- Prefetching only runs in production. In
next devevery click is a real request, so a page that feels slow locally may be instant afternext build && next start. Always judge navigation speed on a production build. - Prefetches expire. If the prefetched data is stale by the time the user hovers the link, Next.js prefetches again. A sidebar with forty links can therefore send a burst of requests on every page load. On a dynamic route each of those is real server work, which is when
prefetch={false}earns its place. - A dynamic route without
loading.tsxcannot be prefetched usefully. There is no boundary to stop at, so the default prefetch has nothing to cache, and the click waits for the server with no feedback. Adding aloading.tsxis usually the fix, notprefetch={true}.
With Partial Prefetching turned on (partialPrefetching: true, Next.js 16.3 and later), the default changes: auto prefetches the route's static shell instead of the full page. That model, along with programmatic router.prefetch(), is the subject of the lesson Streaming, Loading UI and Instant Navigations.
Feedback while a link is pending
When a navigation cannot be instant (prefetching is off, or not finished, or the route is dynamic with no loading.tsx), the user clicks and nothing happens for a moment. They click again. useLinkStatus from next/link fixes that. It returns { pending } for the <Link> it sits inside:
"use client";
import { useLinkStatus } from "next/link";
export function PendingHint() {
const { pending } = useLinkStatus();
// Always rendered, fixed size: only opacity changes, so no layout shift.
return <span aria-hidden className={pending ? "hint is-pending" : "hint"} />;
}import Link from "next/link";
import { PendingHint } from "../_components/PendingHint";
export default function ShopLayout({ children }: LayoutProps<"/shop">) {
return (
<>
<nav>
<Link href="/shop/books" prefetch={false}>
Books <PendingHint />
</Link>
</nav>
{children}
</>
);
}The rules: the hook must be called in a component rendered inside a <Link>, so it is always a small Client Component child. If the route was already prefetched, pending never becomes true. If the user clicks several links quickly, only the last one shows as pending. Treat it as a patch for a slow transition you have measured, then fix the cause with a loading.tsx or better prefetching.
Scroll and focus on navigation
A full page load always starts at the top and moves focus to the document. A client-side transition does neither by default, so you need to know what Next.js does for you and what it leaves to you.
Scroll. The default is closer to "keep your place" than "jump to top". After a navigation, if the new page segment is already visible in the viewport, scroll stays where it is. If it is not visible (you clicked a link in a long footer), Next.js scrolls to the top of the first element of the new page. It skips sticky and fixed elements when it looks for that element, which is why a sticky header does not confuse it. Back and forward navigations restore the previous scroll position, as the browser would.
You can opt out per link or per call:
<Link href="/products?sort=price" scroll={false}>Sort by price</Link>
router.push("/products?page=2", { scroll: false });
<Link href="/docs/routing#dynamic-segments">Jump to a heading</Link>scroll={false} is right for tabs, sort controls and filters, where the user expects to stay put. A hash in the href scrolls to the element with that id, just like a plain anchor.
Focus. This is the part teams get wrong. Next.js includes a route announcer: an invisible live region that tells screen reader users the new page's document.title (falling back to the first <h1>, then the path) after each navigation. It does not move keyboard focus. Focus stays on the link that was clicked, which may now sit in a sidebar that did not change. A keyboard user then has to tab through the whole sidebar again to reach the new content.
Two habits fix most of it. First, give every page a unique title in its metadata, so the announcement is useful (the Metadata and Images lesson covers the title.template pattern). Second, for app-like layouts where the main content changes under a persistent nav, move focus to the content region when the path changes:
"use client";
import { usePathname } from "next/navigation";
import { useEffect, useRef } from "react";
export function FocusMain({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
const ref = useRef<HTMLElement>(null);
const isFirstRender = useRef(true);
useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false; // do not steal focus on first load
return;
}
ref.current?.focus();
}, [pathname]);
return (
<main ref={ref} tabIndex={-1} className="outline-none">
{children}
</main>
);
}tabIndex={-1} makes the element focusable by script without adding it to the tab order. Pair it with a "Skip to content" link at the top of the root layout. Do not apply this to every navigation blindly: moving focus when a filter changes the query string would be disorienting, which is why the effect keys on pathname and not on search params.
Router hooks in Client Components
For navigation in event handlers and for reading the URL in the browser, next/navigation provides hooks. They only work in Client Components (files marked "use client", which you met in Server and Client Components).
| Hook | Gives you | Typical use |
|---|---|---|
useRouter() | push, replace, back, refresh, prefetch | Navigate after a button click or form success |
usePathname() | "/dashboard/settings" | Highlight the active nav link |
useSearchParams() | Read-only URLSearchParams | Read ?sort= for client-side filtering |
useParams() | { slug: "hello" } | Read dynamic params deep in a client tree |
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
export function NavLink({ href, children }: { href: string; children: React.ReactNode }) {
const pathname = usePathname();
const active = pathname === href || pathname.startsWith(href + "/");
return (
<Link href={href} aria-current={active ? "page" : undefined} className={active ? "font-bold" : ""}>
{children}
</Link>
);
}The active check is plain string logic, so you can test it anywhere:
Press Run (⌘ Enter) to see what happens.What does this print?
const pathname = "/docs/routing"; const links = ["/", "/docs", "/doc", "/docs/routing"]; const active = links.filter((h) => h === "/" ? pathname === "/" : pathname === h || pathname.startsWith(h + "/")); console.log(active.length);
Redirects and not found on the server
In Server Components, Server Actions and Route Handlers, you navigate by calling functions from next/navigation:
import { redirect } from "next/navigation";
import { getCurrentUser } from "@/lib/auth";
export default async function AccountPage() {
const user = await getCurrentUser();
if (!user) redirect("/login"); // throws; nothing below runs
return <h1>Hi {user.name}</h1>;
}redirect(path)sends the user elsewhere (a temporary redirect).permanentRedirect(path)does the same with a permanent status, for moved URLs.notFound()renders the nearestnot-found.tsx.
All three work by throwing a special error that Next.js catches. That has one gotcha: if you call them inside a try block, your catch will swallow the redirect. Call them after the try/catch, not inside it. The lesson Error Handling in Next.js covers how these thrown signals interact with error boundaries.
redirect vs permanentRedirect, and the status codes
The choice between the two is a decision about caching and SEO, not style. The status code tells browsers and search engines how long to believe the redirect.
| Situation | redirect() | permanentRedirect() |
|---|---|---|
| Server Component or Route Handler, normal request | 307 Temporary | 308 Permanent |
| Server Action, JavaScript loaded | Client-side navigation, no HTTP redirect | Client-side navigation |
| Server Action, form posted before JavaScript loaded | 303 See Other | 303 See Other |
| Called after streaming has started | A meta tag that redirects on the client | Same |
Why 307 and 308 and not the classic 302 and 301? Many browsers turn a POST into a GET when they follow a 302 or 301. The newer codes promise to keep the method. The Server Action case uses 303 on purpose: after a form POST, you want the browser to GET the next page, so a refresh does not resubmit the form.
Use redirect() for anything that depends on the request: logged out, wrong role, onboarding not finished, "go to the thing you just created". Use permanentRedirect() only when a URL has truly moved for everyone, such as a renamed slug. Browsers may cache a 308 hard, and search engines move the old URL's ranking to the new one. Send a permanent redirect for a login check by mistake and some users keep being bounced from a page they are now allowed to see.
Two more facts worth knowing. redirect defaults to replace in the history stack, except in Server Actions where it defaults to push; you can pass RedirectType.push or RedirectType.replace as the second argument (it has no effect in Server Components). And if a redirect does not depend on rendering at all (an old marketing URL, a whole moved section), put it in redirects() in next.config.ts or in proxy.ts instead, so it happens before any page code runs.
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
async redirects() {
return [
// permanent: true sends 308, false sends 307
{ source: "/blog/old-slug", destination: "/blog/new-slug", permanent: true },
];
},
};
export default nextConfig;The client cache and router.refresh()
Here is a bug report you will see in your first month: "I saved my profile, went back to the dashboard, and it still shows my old name until I reload." The cause is almost always the client cache, and the fix is knowing which of three tools to reach for.
The client cache is an in-memory store in the browser that holds the RSC payload for routes you have visited or prefetched. On a client-side navigation Next.js serves cached layouts and loading states from it without asking the server. It lives only in that tab and disappears on a full reload. The default lifetimes:
- Pages on dynamic routes are not reused at all (the default
dynamicstale time has been 0 seconds since Next.js 15). Every visit asks the server. - Static pages and fully prefetched routes (
prefetch={true}orrouter.prefetch()) are reused for 5 minutes. - Back and forward reuse whatever is cached, whatever its age, so the previous screen comes back instantly with its scroll position.
- Shared layouts are not refetched on navigation at all, only the segment that changed. A layout that shows the user's name keeps showing the old one until something invalidates it.
You can change the lifetimes globally with the experimental staleTimes option in next.config.ts, or per piece of data with the stale value of a cacheLife profile, which the docs now recommend. Cache Components in Depth covers cacheLife properly.
Run the model below. It is a simplified version of the rules above, but it predicts what you will see in the Network tab.
Press Run (⌘ Enter) to see what happens.Three ways to get fresh data on screen
router.refresh() from useRouter() makes a new request for the current route, re-runs its Server Components, and merges the result into the page. Client state survives: useState values, input contents and scroll position stay. It clears the client cache for that route. It does not touch the server-side cache, so if the data comes from a cached function, refresh can return exactly the same output.
A Client Component saves the new name through a Route Handler.
That gives you a simple rule for choosing:
| You changed data in... | Use | Why |
|---|---|---|
| A Server Action, data not cached | refresh() from next/cache | Tells the client router to refetch, from the server side |
| A Server Action, data cached | updateTag() or revalidatePath() | Invalidates the server cache and the client cache together |
| A Client Component (fetch to a Route Handler, third-party SDK) | router.refresh() | Only the browser knows the change happened |
Prefer the Server Action route where you can, because the server knows what changed and can invalidate precisely. The lesson Server Actions and Forms shows updateTag and refresh() in context. Setting or deleting a cookie in a Server Action also clears the client cache, which is why logging out through an action does not leave stale signed-in pages behind.
Parallel and intercepting routes (briefly)
Two advanced conventions you will see in larger apps:
- Parallel routes use
@namefolders, called slots. A layout receives each slot as a prop next tochildren, so one URL can render several independent sections (for example@analyticsand@teampanels on a dashboard), each with its own loading and error states. - Intercepting routes use
(.),(..)or(...)prefixes to show another route inside the current layout. The classic example is a photo feed: clicking a photo opens/photos/42in a modal over the feed, while visiting/photos/42directly (or refreshing) shows the full page.
- app/
- layout.tsxrenders {children} and {modal}
- feed/
- page.tsxthe photo grid
- photos/
- [id]/
- page.tsxfull page for direct visits
- @modal/
- default.tsxrenders null when no modal is open
- (.)photos/
- [id]/
- page.tsxsame photo, shown in a modal on client navigation
You will not need these often, but recognising the folder names saves confusion in an unfamiliar codebase. The lesson Parallel and Intercepting Routes builds the modal pattern step by step, including the default.tsx files Next.js 16 requires for every slot.
Which layouts wrap this page?
Layouts nest by folder. Given a page file and the list of layout files in the project, return the layouts that wrap the page, outermost first.
A layout at <folder>/layout.tsx wraps every page in that folder and below it.
page = "app/(shop)/cart/page.tsx"
layouts = ["app/layout.tsx", "app/(shop)/layout.tsx", "app/blog/layout.tsx"]
→ ["app/layout.tsx", "app/(shop)/layout.tsx"]Highlight the active nav link
A nav bar reads the current path with usePathname() and highlights the matching link. Write isActive(pathname, href).
"/"is active only on the home page.- Any other link is active on its own path and on paths below it (
/blogis active on/blog/my-post), but not on paths that merely start with the same letters (/blogger). - Ignore a trailing slash on either side.
isActive("/blog/post", "/blog") → true
isActive("/blogger", "/blog") → false
isActive("/about", "/") → false- layout
- A
layout.tsxcomponent that wraps child routes viachildrenand stays mounted while you navigate between them. - template
- Like a layout, but remounted on every navigation, so state resets and effects re-run.
- prefetching
- Loading a linked route in the background (in production) when its
Linkenters the viewport, so the click feels instant. - client-side transition
- Navigation that swaps only the changed route segments instead of reloading the whole document.
- redirect()
- A server-side helper from
next/navigationthat throws to send the user to another URL. - parallel route
- An
@slotfolder rendered by a layout alongsidechildren, letting one URL show several independent sections. - useLinkStatus
- A hook from
next/link, used inside aLink, that returns{ pending }while that link's navigation is in progress. - client cache
- The in-memory browser store of RSC payloads for visited and prefetched routes. Cleared on a full reload or by
router.refresh(),refresh(),updateTag()and similar. - router.refresh()
- Re-renders the current route's Server Components on the server and merges the result, keeping client state. Does not invalidate the server cache.
- 307 / 308
- Temporary and permanent redirect status codes that keep the request method.
redirect()sends 307,permanentRedirect()sends 308. - route announcer
- An invisible live region Next.js uses to read the new page title to screen reader users after a client-side navigation.