Next.js Routing and Layouts
Structure an app with the App Router: folders as routes, nested layouts, dynamic segments, loading and error states.
Intermediate · about 8 hours · difficulty 3/5
Learn first: State, Effects and Hooks
Next.js is a React framework that adds routing, server rendering and backend code to React. The App Router (the app directory) is the current default.
Routing by folders
- app/page.tsx is the home page; app/internships/page.tsx is /internships.
- Dynamic segments: app/internships/[id]/page.tsx handles /internships/42.
- Route groups like (marketing) and (dashboard) organise files without changing URLs.
- The Link component handles client-side navigation and prefetching.
Special files
- layout.tsx wraps pages and keeps state across navigation; use it for navbars and dashboard shells.
- loading.tsx shows instantly while a route loads (built on Suspense).
- error.tsx catches errors in a segment so one broken widget does not crash the app.
- not-found.tsx for 404s.
Navigation and URLs
Read params and searchParams in pages for filters and pagination. Keep filter state in the URL so pages can be shared and bookmarked.
Pitfalls
- Putting everything in the root layout, which then re-renders or fetches too much.
- Mixing up the older pages directory tutorials with App Router code. Check which router a tutorial uses.
- Forgetting loading and error states, so slow data shows a blank screen.
You are ready to move on when you can scaffold a Next.js app with a public section and a dashboard section, each with its own layout, dynamic routes, and loading and error files.
Key concepts
- File-based routing
- Layouts and nested layouts
- Dynamic segments and params
- Link and navigation
- loading.tsx and error.tsx
- Route groups
- searchParams for filters
- Parallel and intercepting routes
Mini project
Scaffold a Next.js campus placement portal: public pages (home, companies, company details by slug) and a /dashboard group with a sidebar layout, each with loading and error states.
Check yourself
What is the difference between layout.tsx and page.tsx, and why does a layout not re-mount when you navigate between its child pages?
Free resources
- Next.js Documentation (Next.js)
- Learn Next.js (Next.js)
- App Router (Next.js)