File-based routing, layouts & navigation
Build nested layouts, dynamic routes, loading and error states.
By Invicly Tech, , in Frontend with React & Next.js. About 10 minutes to read.
In short
In the Next.js App Router, folders inside app define URL segments and page.tsx makes a segment visitable. layout.tsx wraps child routes and persists across navigation, while loading.tsx and error.tsx handle waiting and failure.
Explained simply
In a Next.js app, you do not write a list of routes by hand. The folders inside the app directory are the routes. A folder called about with a page.tsx file inside it becomes the page at /about.
Some files have special names. page.tsx is what people see at that address. layout.tsx is a frame that wraps the page, such as a header and sidebar. loading.tsx is shown while the page is getting ready, and error.tsx is shown if something breaks.
Layouts are clever: when you move between pages that share a layout, the layout stays on screen and keeps its state. Only the inside part changes. So a sidebar's scroll position or a search box's text is not lost.
To move between pages, use the Link component instead of a plain a tag. Link loads the next page in the background and swaps it in without a full reload, so navigation feels instant.
Press Play on a diagram to walk through it one step at a time.
- layout.tsx
- Root layout wraps every page
- page.tsx
- URL: /
- blog/
- layout.tsx
- page.tsx is /blog
- loading.tsx
- blog/[slug]/
- page.tsx is /blog/any-slug
- error.tsx
- (marketing)/
- layout.tsx with a big hero header
- pricing/page.tsx is /pricing
- (app)/
- layout.tsx with sidebar
- settings/page.tsx is /settings
- docs/[...slug]/
- page.tsx is /docs/a/b/c
- _components/
- Not routable, shared UI
- not-found.tsx and global-error.tsx
- App-wide 404 and crash screens
In depth
The special files and how they nest
Each route segment can have its own set of special files, and Next.js wraps them in a fixed order. From outside to inside: layout.tsx, then template.tsx, then an error boundary built from error.tsx, then a Suspense boundary built from loading.tsx, then a not-found boundary from not-found.tsx, and finally page.tsx. A child segment's layout sits inside its parent's page slot.
This order explains real behavior. An error in a page is caught by the error.tsx in the same folder, but an error in that folder's layout is caught by the parent's error.tsx, because the boundary sits inside the layout. template.tsx is like a layout that remounts on every navigation, useful for enter animations. The root layout must render the html and body tags.
- 1layout.tsx
Persists across navigation
- 2template.tsx
Optional; remounts on each navigation
- 3error.tsx boundary
Catches errors below it
- 4loading.tsx boundary
Suspense fallback while the page loads
- 5not-found.tsx boundary
Shown when notFound() is called
- 6page.tsx
The unique content for this URL
Dynamic segments in depth
A folder in square brackets matches any value: app/products/[id] serves /products/42. A catch-all [...slug] matches several parts, so app/docs/[...slug] serves /docs/a/b/c with slug as ["a", "b", "c"]. Double brackets [[...slug]] make it optional, so /docs matches too.
In current Next.js, params and searchParams are promises in pages and layouts: you write const { id } = await params. To build pages ahead of time, export generateStaticParams and return the list of params, for example every product id; Next.js renders those at build time. Call notFound() from next/navigation when the id does not exist, and the nearest not-found.tsx is shown with a 404 status.
- [id]: one segment
- [...slug]: one or more segments
- [[...slug]]: zero or more segments
- generateStaticParams pre-renders known values
Organizing without changing URLs
Some folder names do not become part of the URL. A route group is a folder in parentheses, such as (marketing) or (dashboard). It lets you group routes and give each group its own layout, so the marketing pages and the app pages can look completely different while URLs stay /pricing and /settings.
A private folder starts with an underscore, such as _components, and is never routable, which is a safe place for files that belong to a route but are not pages. Advanced patterns also exist: parallel routes use @folder slots to render two pages in one layout, and intercepting routes like (.)photo show a page as a modal while keeping a real URL. Learn the basics first; reach for these when a design needs them.
How navigation and prefetching work
The Link component renders a real a tag, so it works without JavaScript and for screen readers. Once the app is running, clicking it fetches only the data for the new route (the React Server Component payload), not a full HTML page, and React swaps in the changed segments while shared layouts stay.
In production, Next.js prefetches links when they scroll into view. For static routes it prefetches the whole route; for dynamic routes it prefetches down to the nearest loading.tsx, so the loading state can appear instantly. In client components, useRouter from next/navigation gives push, replace, back and refresh for navigation in code, such as after a form succeeds. usePathname and useSearchParams read the current URL. In server components and actions, use redirect() instead.
- Browser (Next.js router) to Server: prefetch when the link is visible1prefetch when the link is visible
- Server to Browser (Next.js router): route payload up to loading.tsx2route payload up to loading.tsx
- User to Browser (Next.js router): click3click
- Browser (Next.js router) to User: show loading state at once, layout stays4show loading state at once, layout stays
- Browser (Next.js router) to Server: fetch the rest of the page data5fetch the rest of the page data
- Server to Browser (Next.js router): stream the page content6stream the page content
Error handling that users can recover from
error.tsx must be a client component, so it starts with "use client". It receives the error and a reset function; calling reset tries to render the segment again, which helps with temporary failures. In production, the message of errors thrown in server components is hidden from the browser for security, and you get a digest id you can match with your server logs.
Errors in the root layout cannot be caught by app/error.tsx, because the boundary sits inside the layout. For that, add app/global-error.tsx, which replaces the whole document and must render its own html and body. For expected problems, such as a missing product or a failed validation, do not throw: return a message or call notFound(). Throwing is for unexpected failures.
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Create routes with the app directory~50m
- 2Add nested layouts~50m
- 3Build dynamic route segments~50m
- 4Add loading.tsx and error.tsx~50m
- 5Navigate with Link and useRouter~50m
Key points
- A folder becomes a route segment only when it contains page.tsx.
- Layouts nest and keep their state when you navigate between child pages.
- Square brackets like [slug] create dynamic segments read from params.
- Use Link for navigation; it prefetches routes and avoids full page reloads.
- useRouter from next/navigation handles programmatic navigation in client components.
Key terms
Tap a card to flip it. 0/6 known
Examples
// app/blog/[slug]/page.tsx
import Link from 'next/link';
type Props = { params: Promise<{ slug: string }> };
export default async function Post({ params }: Props) {
const { slug } = await params;
return (
<article>
<h1>{slug}</h1>
<Link href="/blog">Back to blog</Link>
</article>
);
}A dynamic route reading its slug and linking back.
A product page with static params and a 404
Step 1: generateStaticParams returns all known ids, so those pages are built ahead of time. Step 2: the page awaits params and loads the product. Step 3: if it is missing, notFound() shows the nearest not-found.tsx with a real 404 status, which search engines understand. Step 4: a loading.tsx next to the page covers slow loads.
// app/products/[id]/page.tsx
import { notFound } from "next/navigation";
import { getProduct, getProductIds } from "@/lib/products";
export async function generateStaticParams() {
const ids = await getProductIds();
return ids.map((id) => ({ id }));
}
export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const product = await getProduct(id);
if (!product) notFound();
return <h1>{product.name}</h1>;
}An error screen with a retry button
Step 1: create error.tsx in the dashboard folder and mark it "use client". Step 2: log the error, for example to your monitoring tool, in an effect. Step 3: show a friendly message and a Try again button that calls reset. If the dashboard's data fetch fails, only the dashboard area shows this screen; the root layout with the navigation keeps working.
// app/dashboard/error.tsx
"use client";
import { useEffect } from "react";
export default function DashboardError({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) {
useEffect(() => {
console.error(error);
}, [error]);
return (
<div role="alert">
<h2>Could not load your dashboard.</h2>
<button onClick={() => reset()}>Try again</button>
</div>
);
}Quick reference
- A folder is a URL segment; it is public only when it contains page.tsx
- params and searchParams are promises: const { id } = await params
- (group) folders organize routes and layouts without changing the URL
- _folder is private and never becomes a route
- error.tsx needs "use client"; root layout errors need global-error.tsx
- notFound() shows not-found.tsx with a 404; redirect() works in server code
- Link prefetches visible links in production; useRouter is for client-side code
- generateStaticParams pre-renders dynamic routes at build time
Common mistakes
- Using a plain anchor tag for internal links and losing client-side navigation.
- Forgetting that error.tsx must be a client component.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Create the files for /, /about and /blog, where /blog has its own layout with a sidebar that does not appear on /about.
- Exercise 2medium
Add a dynamic route /blog/[slug] that reads the slug, shows a loading state while it loads, and returns a 404 for unknown posts.
- Exercise 3hard
Split an app into marketing pages (/, /pricing) with a hero layout and app pages (/dashboard, /settings) with a sidebar layout, each with its own error screen.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between the App Router and the Pages Router?
- The App Router (app directory) is the current model, with server components, nested layouts and streaming. The Pages Router (pages directory) is the older model and is still supported, but new projects should use the App Router.
- Should I use Link or an a tag in Next.js?
- Use Link for links inside your app; it renders an a tag but adds prefetching and client-side navigation. Use a plain a tag for external sites.
- Why are params a Promise in Next.js?
- Since Next.js 15, params and searchParams are async so Next.js can start rendering before they are needed. Await them in server components, or use React's use() in client components.