The App Router: File-System Routing, Layouts & Templates
The Next.js App Router relies on a file-system hierarchy inside the app directory. Every directory represents a URL segment. Special files define UI behavior for that segment: page.tsx renders the primary route UI, layout.tsx creates shared structural shells across sub-routes, loading.tsx supplies instant streaming loading boundaries, and error.tsx catches runtime exceptions.
Layouts preserve state across route transitions and do not re-render parent trees when navigating between sibling routes. In contrast, template.tsx creates a fresh component instance on every navigation, making it ideal for page enter animations or logging hooks. Route groups (folders named (group)) organize files without altering the public URL path.
Exercise
Build an app directory layout with a shared nav header and a dynamic app/dashboard/[teamId]/page.tsx route that displays the team ID from route params.
Check your understanding
What is the difference between layout.tsx and template.tsx in Next.js?Show answerHide answer
Answer
layout.tsx preserves its state and DOM across navigation between sibling sub-routes, while template.tsx re-mounts and creates a new instance on every route change.How do route groups ((groupName)) change the URL structure?Show answerHide answer
Answer
Route groups organize files into logical directories without adding their folder names to the public URL path.