Create a new Next.js app:
npx create-next-app@latest my-nextjs-app
cd my-nextjs-app
A concise cheat sheet covering essential Next.js concepts, commands, and best practices for building efficient and scalable React applications.
Create a new Next.js app:
|
Start the development server:
|
Build for production:
|
Start the production server:
|
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 |
|
Files in the
|
Import |
|
Usage |
|
Prefetching |
The |
Use bracket syntax Access the route parameters using the
|
Import |
|
Properties |
|
Next.js provides several data fetching methods for different use cases:
|
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. |
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. |
Description |
Specifies which dynamic routes to pre-render at build time. Required for dynamic routes when using |
Usage |
|
Fallback Options |
|
Create API endpoints by creating files in the
API routes are server-side only and won’t increase your client-side bundle size. |
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 |
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 |
Example |
|
Matcher |
The |