Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Next.js App Router File Conventions: page, layout, template, and the Rest

Layouts persist and templates remount; only page.tsx and route.ts make a segment routable. Route groups, private folders, and the boundaries that catch what.

~5 min readNext.js
#Next.js#App Router#Routing#React
3D illustration of an App Router folder tree with page and layout file cards nesting around each other

Quick Summary

The App Router is a filesystem convention. A folder under app/ becomes a route segment by its name, and the files inside it decide what that segment renders: page.tsx makes the segment publicly routable, layout.tsx wraps it and persists across navigations, template.tsx wraps it and remounts on every navigation, loading.tsx supplies a Suspense fallback, error.tsx catches render errors, not-found.tsx handles notFound(), and route.ts turns the segment into an HTTP endpoint instead of a page.

Three rules explain most of the confusion. A folder without a page.tsx or route.ts is not routable, no matter how many other files it has. The root layout is required, must be at app/layout.tsx, and must render <html> and <body>. And the hierarchy is nested, not merged: every layout between the root and the page wraps the page, and each one re-renders only when its own segment changes.

Names starting with _ are opt-outs (not routable), (name) is a route group that organises files without adding a URL segment, and @name is a parallel route slot. Those three bracket conventions are how a large app keeps URLs stable while the folder tree evolves.

Basic Syntax & Core Signatures

text
app/ layout.tsx # required root layout: <html> and <body> page.tsx # "/" globals.css (marketing)/ layout.tsx # nested layout, no URL segment about/page.tsx # "/about" pricing/page.tsx # "/pricing" (app)/ layout.tsx # a second shell: sidebar dashboard/ layout.tsx # "/dashboard/*" wrapper page.tsx # "/dashboard" settings/page.tsx # "/dashboard/settings" blog/ layout.tsx page.tsx # "/blog" [slug]/ page.tsx # "/blog/:slug" loading.tsx error.tsx not-found.tsx _components/card.tsx # not routable api/ health/route.ts # "/api/health"
tsx
// app/layout.tsx — the only required file, runs for every route export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html lang="en"> <body>{children}</body> </html> ); } // app/blog/[slug]/page.tsx — Next.js 15+: params is a Promise export default async function BlogPost({ params }: { params: Promise<{ slug: string }> }) { const { slug } = await params; const post = await getPost(slug); return <article>{post.title}</article>; } // app/blog/[slug]/template.tsx — remounts on every navigation under this segment export default function Template({ children }: { children: React.ReactNode }) { return <div className="fade-in">{children}</div>; } // app/api/health/route.ts — an endpoint, not a page export async function GET() { return Response.json({ ok: true, ts: Date.now() }); }
tsx
// Route segment config: applies to this segment and its children export const dynamic = "force-dynamic"; // or "auto" | "force-static" | "error" export const revalidate = 60; // seconds; false = never export const runtime = "nodejs"; // or "edge" export const maxDuration = 30; // seconds (platform-dependent) export const dynamicParams = true; // allow params outside generateStaticParams

Key Comparison Table

FileRoutableRendersPersists across navigationErrors caught
page.tsxYesThe route's contentNoBy the nearest error.tsx
layout.tsxNoShell wrapping childrenYes — state kept, does not re-renderNo (falls to parent)
template.tsxNoShell wrapping childrenNo — remounts each navigationNo
loading.tsxNoSuspense fallback for the segmentn/aNo
error.tsxNoClient error boundary UIn/aYes, for its subtree
global-error.tsxNoFull-document boundaryn/aYes, including the root layout
not-found.tsxNoUI for notFound()n/an/a
route.tsYes (as an endpoint)HTTP responsen/aBy you
Folder conventionURL effectPurpose
about/Adds /aboutOrdinary segment
[slug]/Adds /[slug]Dynamic segment
[...slug]/Adds catch-allOne or more segments
[[...slug]]/Adds optional catch-allZero or more segments
(group)/No changeRoute group with its own layout
_private/ExcludedNon-routable files and helpers
@slot/No changeParallel route slot
(.)photo/No changeIntercepting route

Practical Edge Cases & Deep Dives

1. Layout versus template: the state that survives navigation

A layout does not unmount when the route below it changes. A collapsible sidebar with useState in a layout keeps its state as you move from /dashboard to /dashboard/settings, and the layout is not re-rendered on that navigation. A template is the opposite: it is a new instance per navigation, so its state resets and an entrance animation replays.

tsx
// app/dashboard/layout.tsx — state survives; good for chrome "use client"; export default function DashboardLayout({ children }: { children: React.ReactNode }) { const [open, setOpen] = useState(true); // preserved across /dashboard/* return <aside data-open={open}>{children}</aside>; }

Use a template for page-transition animation, for useEffect that must run per navigation, or for a form whose state must not leak between records. Do not use a template to force a data refresh — revalidation is the tool for that, and a template does not reset server-side caches.

2. Layouts cannot read searchParams

tsx
// app/shop/layout.tsx export default function ShopLayout({ searchParams }: { searchParams: { q?: string } }) { // Never populated. Layouts do not receive searchParams. return <div>{searchParams.q}</div>; }

The layout sits outside the page's dynamic boundary, so search parameters are not available there. Reading them in a client component with useSearchParams() works but opts the whole subtree out of static rendering unless it sits under a <Suspense> boundary. The usual fixes: move the parameter-dependent UI into the page, read it in a client component wrapped in Suspense, or use a template plus a client hook when the UI truly must be a shell above the page.

3. Route groups: two shells, one URL space

(marketing) and (app) let two different root-level layouts coexist — a marketing layout without a sidebar and an app layout with one — while keeping /about and /dashboard as ordinary URLs. Two constraints follow: a route may not resolve to two groups that both define a conflicting page.tsx at the same path (build error), and each group that defines its own <html> must be a root layout, which means the top-level app/layout.tsx must not exist if the groups own the document.

text
app/(marketing)/layout.tsx -> <html><body> for the marketing shell app/(app)/layout.tsx -> <html><body> for the app shell # both are root layouts because app/layout.tsx is absent

4. loading.tsx is a Suspense boundary, and it replaces the whole segment

loading.tsx wraps the segment's page in a Suspense boundary and shows while the page's data resolves on the server. Two consequences: the fallback replaces the page, so a spinner that hides the page's layout should live in a nested loading.tsx rather than the top one; and a route with a very fast response still ships the fallback, causing a flash. For finer control, drop loading.tsx and place <Suspense fallback={...}> around the specific slow component — streaming then keeps the rest of the page interactive sooner.

tsx
export default async function Page() { const slow = getSlowData(); // do not await yet return ( <section> <h1>Dashboard</h1> <Suspense fallback={<TableSkeleton />}> <Table data={slow} /> </Suspense> </section> ); }

5. page.tsx and route.ts cannot share a segment

text
app/api/users/page.tsx -> page at /api/users app/api/users/route.ts -> handler at /api/users # both present: build error, conflicting route resolution

A segment is either a page or an endpoint. route.ts also cannot coexist with page.tsx in the same folder, and a route handler does not inherit layouts — it is an HTTP function, not a React tree. That is why an API folder nested under a layout-heavy path still returns plain JSON with no shell.

Common Runtime & Configuration Mistakes

SymptomCauseFix
404 for a folder that existsNo page.tsx or route.tsAdd the file; _ folders are private
You should not have <html> in a nested layoutA layout below the root renders <html>Only the root layout does
Layout state resets unexpectedlyA template.tsx is in the treeUse layout.tsx for persistent state
Layout crashes and nothing catches iterror.tsx does not catch layout errorsMove the boundary up, or use global-error.tsx
Infinite redirect or blank pageA route group resolves two pages to one URLRemove the duplicate path
Build error: conflicting routepage.tsx and route.ts in one folderSplit the segment
searchParams undefined in a layoutLayouts do not receive themRead them in the page or a client component
Static page becomes dynamiccookies()/headers() used in the treeMove it behind Suspense or accept dynamic rendering
Params typed as an object failNext.js 15+ uses Promisesawait params in pages and handlers
Loading flash on fast routesTop-level loading.tsx on a quick segmentNest it, or use <Suspense> locally

The convention files are the app's routing contract, and every one of them has an exact meaning: a layout persists, a template remounts, a page routes, a route answers HTTP, and a boundary catches. When a URL, a shell, or an error handler behaves unexpectedly, the answer is which file in that folder tree the framework actually chose.

Try matching browser tools

All tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.