Overview
Next.js App Router uses a file-based routing system where the file structure in theapp
directory directly maps to URL routes. This approach simplifies routing configuration and provides better performance through automatic code splitting.
Key Concepts
Key Concepts
Route Segments
Each folder in theapp
directory represents a route segment:Special Files
page.tsx
- Makes a route publicly accessible
- Required for a route to be accessible
- Defines the UI for that route
layout.tsx
- Shared UI for multiple pages
- Wraps child layouts and pages
- Maintains state during navigation
loading.tsx
- Loading UI for a route segment
- Shows while page is loading
- Automatically wraps page and children
error.tsx
- Error UI for a route segment
- Catches errors in child segments
- Provides error boundaries
not-found.tsx
- 404 page for a route segment
- Shows when route is not found
- Can be nested at different levels
template.tsx
- Re-renders on every navigation
- Useful for animations and transitions
- Creates new instance for each route
Route Groups
Route Groups
Use parentheses to group routes without affecting the URL structure:
Navigation
Navigation
Best Practices
Best Practices
Route Organization
1
Group Related Routes
Use route groups to organize related pages without affecting URLs
2
Use Descriptive Names
Choose clear, descriptive folder and file names
3
Keep Routes Flat
Avoid deeply nested routes when possible
4
Use Dynamic Routes Wisely
Use dynamic routes for content that changes frequently
Performance Considerations
Automatic Code Splitting
- Each route is automatically code-split
- Only loads code needed for current route
- Improves initial page load performance
Prefetching
- Links are automatically prefetched
- Improves navigation performance
- Can be disabled with prefetch=
Troubleshooting
Troubleshooting
Route Not Found
Route Not Found
Problem: Route returns 404 even though file exists
Solution: Ensure the file is named
page.tsx
and is in the correct directoryLayout Not Applying
Layout Not Applying
Problem: Layout styles not showing on child routes Solution: Check
that layout.tsx is in the correct directory and wraps children
Dynamic Route Not Working
Dynamic Route Not Working
Problem: Dynamic route parameters not accessible
Solution: Ensure the page component receives params as props and handles the correct parameter names
Key Takeaway: Next.js file-based routing simplifies route management by
using the file system structure to define routes. This approach provides
better performance through automatic code splitting and makes routing more
intuitive for developers.