Next.js Cheatsheet
Learn the key concepts of Next.js with short explanations and examples. Perfect for students moving from React to full-stack web apps with Next.js.
App Router (Next.js 13+)
The App Router uses the app/ directory. Components are Server Components by default.
// app/page.js
export default function Page() {
return <h1>Hello, App Router!</h1>;
}
// app/layout.js
export default function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
);
}Server vs Client Components
All components are Server Components by default. Add 'use client' at the top to use hooks or interactivity.
'use client';
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}Data Fetching (App Router)
You can fetch data directly in Server Components using async/await.
async function getData() {
const res = await fetch('https://api.example.com/data');
return res.json();
}
export default async function Page() {
const data = await getData();
return <main>{data.title}</main>;
}Metadata (App Router)
Export a metadata object to define tags like title and description.
export const metadata = {
title: 'My Page',
description: 'Generated by create next app',
};
export default function Page() {}Pages Router (Legacy)
Next.js uses file-based routing. Every file in the pages/ directory becomes a route automatically.
// pages/about.js
export default function About() {
return <h1>About Page</h1>;
}Navigation with Link
Use the Link component for client-side navigation without page reloads.
import Link from "next/link";
<Link href="/about">Go to About</Link>Static Generation
Use getStaticProps to fetch data at build time. Great for blogs or docs where content doesn’t change often.
export async function getStaticProps() {
return {
props: {
message: "Hello from SSG"
}
};
}Server-Side Rendering
Use getServerSideProps to fetch data on each request. Perfect for dashboards or frequently updated data.
export async function getServerSideProps() {
return {
props: {
time: new Date().toISOString()
}
};
}Dynamic Routes
Brackets in filenames make dynamic routes. Example: pages/posts/[id].js.
// pages/posts/[id].js
import { useRouter } from "next/router";
export default function Post() {
const router = useRouter();
return <h1>Post: {router.query.id}</h1>;
}API Routes
You can create backend endpoints inside pages/api/. Great for small APIs or server logic.
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ message: "Hello API" });
}Static Assets
Store images, fonts, and other files in the public/ folder. Access them directly by URL.
<img src="/logo.png" alt="Logo" />Head for SEO
Use the Head component from Next.js to add metadata like title and description for SEO.
import Head from "next/head";
<Head>
<title>My Page</title>
</Head>Image Optimization
The next/image component automatically optimizes images for performance and responsiveness.
import Image from "next/image";
<Image src="/logo.png" width={200} height={100} alt="Logo" />Middleware
Middleware lets you run code before a request is completed. Useful for authentication, logging, or redirects.
// middleware.js
export function middleware(req) {
return NextResponse.redirect(new URL("/login", req.url));
}Incremental Static Regeneration (ISR)
Update static pages after build time by adding a revalidate prop (in seconds).
export async function getStaticProps() {
return {
props: { data },
revalidate: 60, // Revalidate every 60 seconds
};
}Server Actions
Execute server-side code directly from Client Components or forms.
async function create(formData) {
'use server';
const id = await createItem(formData);
}
<form action={create}>...</form>Environment Variables
Store secrets in .env.local. Access them with process.env. Prefix with NEXT_PUBLIC_ to expose to the browser.
NEXT_PUBLIC_API_URL=https://api.example.com
const url = process.env.NEXT_PUBLIC_API_URL;Deployment
Next.js apps can be easily deployed on Vercel, the creators of Next.js. Just push to GitHub and connect your repo.
How to use this page
- Explore the modern App Router features first.
- Understand the difference between Server and Client Components.
- Use
getStaticPropsif you are using the Pages Router. - Learn how to handle metadata and image optimization.
- Deploy on Vercel when your app is ready!
🚀 Explore More Free Developer Tools
Don’t stop here! Supercharge your workflow with our other powerful converters & formatters.
📚 HTML Cheatsheet
HTML Cheatsheet
📚 SCSS Cheatsheet
SCSS Cheatsheet
📚 Javascript Cheatsheet
Javascript Cheatsheet
💡 New tools are added regularly — bookmark DevUtilsX and stay ahead!
Want to support my work?
Buy me a coffee