Catalog / Next.js Cheat Sheet
Next.js Cheat Sheet
A concise cheat sheet covering essential Next.js concepts, commands, and best practices for building efficient and scalable React applications.
Getting Started & Basic Concepts
Project Setup
Create a new Next.js app:
|
Start the development server:
|
Build for production:
|
Start the production server:
|
Key Concepts
Pages |
Files in the |
Components |
Reusable pieces of UI. Can be functional components or class components. |
Layouts |
Components that wrap pages to provide a consistent UI structure across different routes. Often implemented using a |
API Routes |
Serverless functions defined in |
File Structure
|
Routing & Navigation
Basic Routing
Files in the
|
Link Component
Import |
|
Usage |
|
Prefetching |
The |
Dynamic Routes
Use bracket syntax Access the route parameters using the
|
useRouter Hook
Import |
|
Properties |
|
Data Fetching
Data Fetching Methods
Next.js provides several data fetching methods for different use cases:
|
getStaticProps
Description |
Fetches data at build time. Ideal for content that doesn’t change frequently (e.g., blog posts, marketing pages). |
Usage |
|
When to Use |
Use when you can pre-render the page at build time based on the data. |
getServerSideProps
Description |
Fetches data on each request. Use for data that changes frequently or requires authentication. |
Usage |
|
When to Use |
Use when you need to fetch data on every request, such as when you have user-specific data or data that updates very frequently. |
getStaticPaths
Description |
Specifies which dynamic routes to pre-render at build time. Required for dynamic routes when using |
Usage |
|
Fallback Options |
|
API Routes and Middleware
API Route Basics
Create API endpoints by creating files in the
API routes are server-side only and won’t increase your client-side bundle size. |
API Route Handler
Example |
|
Request Object ( |
Contains information about the incoming request, such as headers, query parameters, and body. |
Response Object ( |
Used to send a response back to the client. Includes methods like |
Middleware
Next.js 13+ introduced Middleware to run code before a request is completed. You can rewrite, redirect, add headers, or even block requests based on the incoming request. Create a |
Middleware Example
Example |
|
Matcher |
The |