Introduction
Next.js is a popular React framework used to build fast, user-friendly, and SEO-friendly web applications. It adds many features on top of React, such as server-side rendering, routing, and API support. This cheatsheet covers the important features of Next.js in a simple way, with definitions, small code examples, and key points to remember.
1. Project Setup
Definition: Start a new Next.js project using the command line.
npx create-next-app my-app
cd my-app
npm run dev
Important Point:
This starts the development server at http://localhost:3000
.
2. Pages and Routing
Definition: Files inside the pages/
folder automatically become routes.
// pages/about.js
export default function About() {
return <h1>About Page</h1>;
}
Important Point
The file name becomes the route. Example: pages/contact.js
→ /contact
route.
3. Linking Between Pages
Definition: Use the Link
component from next/link
to move between pages.
import Link from 'next/link';
<Link href="/about">Go to About</Link>
Important Point
This enables fast navigation without full page reloads.
4. Static Generation (SSG)
Definition: Pages are generated at build time and served as static HTML.
export async function getStaticProps() {
return {
props: { message: 'Hello from static props' },
};
}
Important Point
Use getStaticProps
for better performance when data does not change often.
5. Dynamic Routes
Definition: Use square brackets in file names for dynamic routing.
// pages/posts/[id].js
export default function Post({ id }) {
return <h1>Post ID: {id}</h1>;
}
export async function getStaticPaths() {
return {
paths: [{ params: { id: '1' } }],
fallback: false,
};
}
export async function getStaticProps({ params }) {
return {
props: { id: params.id },
};
}
Important Point
Dynamic routes need both getStaticPaths
and getStaticProps
for SSG.
6. Server-Side Rendering (SSR)
Definition: Page is rendered on each request using server-side logic.
export async function getServerSideProps() {
return {
props: { time: new Date().toISOString() },
};
}
Important Point
Use SSR when content changes frequently or based on request.
7. API Routes
Definition: Create backend APIs using files inside the pages/api
folder.
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ message: 'Hello API' });
}
Important Point
No need for a separate backend server; API routes run on the server.
8. Static Assets
Definition: Place images and other files in the public/
folder.
<img src="/logo.png" alt="Logo" />
Important Point
Files in public/
are accessible at the root URL.
9. Head Tag Management
Definition: Use the Head
component from next/head
to manage HTML <head>
content.
import Head from 'next/head';
<Head>
<title>My Page Title</title>
</Head>
Important Point
This is used to add meta tags, title, and SEO information.
10. Image Optimization
Definition: Use the built-in next/image
for optimized image loading.
import Image from 'next/image';
<Image src="/logo.png" width={200} height={100} alt="Logo" />
Important Point
Images are automatically resized and lazy-loaded.
11. Custom 404 Page
Definition: Create a 404.js
file inside pages/
to show a custom not-found page.
// pages/404.js
export default function NotFound() {
return <h1>Page Not Found</h1>;
}
Important Point
Next.js uses this page when a route does not exist.
12. Custom App Component
Definition: Use _app.js
to wrap all pages with common layout or logic.
// pages/_app.js
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
Important Point
Useful for global styles, layout, and state providers.
13. Custom Document
Definition: Use _document.js
to customize the HTML document structure.
// pages/_document.js
import { Html, Head, Main, NextScript } from 'next/document';
export default function Document() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
Important Point
Used only on the server side. Useful for adding fonts or scripts.
14. Environment Variables
Definition: Store secret or config values in .env.local
.
NEXT_PUBLIC_API_URL=https://api.example.com
Usage
const url = process.env.NEXT_PUBLIC_API_URL;
Important Point
Variables must start with NEXT_PUBLIC_
to be available on the client side.
15. Middleware (Advanced)
Definition: Code that runs before a request is completed. Useful for auth, redirects, etc.
// middleware.js
import { NextResponse } from 'next/server';
export function middleware(request) {
return NextResponse.next();
}
Important Point
Middleware runs at the edge. Keep it lightweight.
16. Layouts with getLayout
Pattern
Definition: Use layouts to wrap pages in a common structure (like header, footer, sidebar).
// components/Layout.js
export default function Layout({ children }) {
return (
<>
<header>Header</header>
<main>{children}</main>
<footer>Footer</footer>
</>
);
}
// pages/about.js
import Layout from '../components/Layout';
function AboutPage() {
return <div>About</div>;
}
AboutPage.getLayout = function getLayout(page) {
return <Layout>{page}</Layout>;
};
export default AboutPage;
// pages/_app.js
export default function MyApp({ Component, pageProps }) {
const getLayout = Component.getLayout || ((page) => page);
return getLayout(<Component {...pageProps} />);
}
Important Point
This gives flexibility to use different layouts for different pages.
17. Redirects
Definition: Automatically redirect from one path to another.
// next.config.js
module.exports = {
async redirects() {
return [
{
source: '/old-page',
destination: '/new-page',
permanent: true,
},
];
},
};
Important Point
Use permanent: true
for 301 (SEO-friendly), false
for 302 redirects.
18. Rewrites
Definition: Keep the URL the same, but load a different backend route.
// next.config.js
module.exports = {
async rewrites() {
return [
{
source: '/blog/:slug',
destination: 'https://external.com/blog/:slug',
},
];
},
};
Important Point
Useful for proxying external APIs without changing the frontend URL.
19. Incremental Static Regeneration (ISR)
Definition: Rebuild static pages after a set time, without rebuilding the whole site.
export async function getStaticProps() {
return {
props: { data: 'some data' },
revalidate: 10, // in seconds
};
}
Important Point
Useful for pages that update often but don't need SSR.
20. Catch-All Routes
Definition: Handle dynamic routes with multiple segments.
// pages/docs/[...slug].js
export default function Docs({ slug }) {
return <div>{slug.join('/')}</div>;
}
export async function getStaticPaths() {
return {
paths: [{ params: { slug: ['intro'] } }],
fallback: false,
};
}
export async function getStaticProps({ params }) {
return {
props: { slug: params.slug },
};
}
Important Point
Use [...slug]
for multiple path segments like /docs/intro/setup
.
21. Loading State (Fallback Pages)
Definition: Show a loading message when a dynamic page is being built on the fly.
export async function getStaticPaths() {
return {
paths: [],
fallback: true,
};
}
export default function Post({ post }) {
const router = useRouter();
if (router.isFallback) {
return <div>Loading...</div>;
}
return <div>{post.title}</div>;
}
Important Point
Used with ISR or lazy static paths.
22. Custom Error Handling
Definition: Customize the error page for status codes like 500.
// pages/_error.js
function Error({ statusCode }) {
return (
<p>
{statusCode
? `An error ${statusCode} occurred`
: 'An unexpected error occurred'}
</p>
);
}
Error.getInitialProps = ({ res, err }) => {
const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
return { statusCode };
};
export default Error;
Important Point
Can show friendly error messages and track errors.
23. Global CSS and CSS Modules
Global CSS
// pages/_app.js
import '../styles/global.css';
CSS Modules
/* styles/Home.module.css */
.title {
color: blue;
}
import styles from '../styles/Home.module.css';
<h1 className={styles.title}>Hello</h1>
Important Point
Global CSS is only allowed in _app.js
. Use modules for scoped styles.
24. TypeScript Support
Definition: Next.js has built-in support for TypeScript.
touch tsconfig.json
npm install --save-dev typescript @types/react @types/node
Important Point
Next.js auto-generates a basic tsconfig.json
and starts using .tsx
files.
25. Deployment with Vercel
Definition: You can deploy Next.js apps directly to Vercel.
# If you have Vercel CLI
vercel
Important Point
Vercel is the official platform for Next.js with built-in optimization support.
26. Internationalization (i18n)
Definition: Add support for multiple languages.
// next.config.js
module.exports = {
i18n: {
locales: ['en', 'fr'],
defaultLocale: 'en',
},
};
Important Point
Next.js automatically handles routes like /fr/about
.
27. useRouter
Hook
Definition: Use this React hook from next/router
to access the current route and navigate programmatically.
import { useRouter } from 'next/router';
const router = useRouter();
router.push('/about');
Important Point
You can read query parameters (router.query
) or trigger navigation on events like form submission.
28. next/script
for Third-party Scripts
Definition: Optimized loading of third-party scripts like analytics.
import Script from 'next/script';
<Script src="https://example.com/script.js" strategy="lazyOnload" />
Important Point
Use strategy="lazyOnload"
or strategy="beforeInteractive"
for performance tuning.
29. Fonts Optimization
Definition: Next.js automatically optimizes Google Fonts if used like this:
// _app.js
import { Inter } from 'next/font/google';
const inter = Inter({ subsets: ['latin'] });
Important Point
Avoids layout shift and speeds up font loading by default.
30. Absolute Imports and Module Aliases
Definition: Set up custom import paths for cleaner code.
// jsconfig.json or tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/components/*": ["components/*"]
}
}
}
// Usage
import Header from '@/components/Header';
Important Point
Improves maintainability in large projects.
31. Analytics with Next.js
Definition: Easily integrate analytics like Google Analytics or Vercel Analytics.
// pages/_app.js
import Script from 'next/script';
<Script
strategy="afterInteractive"
src={`https://www.googletagmanager.com/gtag/js?id=GA_TRACKING_ID`}
/>
Important Point
Load scripts after interactive to reduce initial blocking.
32. App Router (New in Next.js 13+)
App Router uses React Server Components by default. Each file is server-rendered unless marked as 'use client'
.
Definition: A new routing system using the /app
directory.
/app/page.js → Home page
/app/about/page.js → About page
/app/layout.js → Shared layout
Important Point
App Router introduces Server Components, React Suspense, and nested layouts. It's the future of Next.js but requires learning new patterns.
33. Parallel Routes and Intercepting Routes (App Router)
Definition: Advanced routing patterns for handling multiple layouts or modals.
/app/@team/page.js
/app/@settings/page.js
Important Point
Use this when building dashboards or apps with side panels, tabs, or overlays.
34. Middleware Conditionals (Path Matching)
Definition: Run middleware logic only for specific routes.
// middleware.js
export const config = {
matcher: ['/dashboard/:path*', '/admin/:path*'],
};
Important Point
Prevents middleware from running globally.
35. Preview Mode
Definition: Let content editors preview draft content using getStaticProps
.
export async function getStaticProps(context) {
if (context.preview) {
// Fetch draft data
}
}
// /api/preview.js
export default function handler(req, res) {
res.setPreviewData({});
res.end('Preview mode enabled');
}
Important Point
Works great with headless CMS like Sanity, Contentful, or Strapi.
36. Build-Time Image Imports (Static Imports)
Definition: Import images for better optimization.
import logo from '../public/logo.png';
<Image src={logo} alt="Logo" />
Important Point
Static image imports give better type safety and performance.
37. fallback: "blocking"
(SSG)
Definition: Generate static pages on the first request and then cache them.
export async function getStaticPaths() {
return {
paths: [],
fallback: 'blocking',
};
}
Important Point
Unlike fallback: true
, this waits for data before serving the page—no loading state needed.
38. Export Static Site
Definition: Generate a 100% static HTML export using next export
.
next build
next export
Important Point
Only works if your site uses only getStaticProps
and no API routes or SSR.
39. Incremental Adoption (Hybrid Pages)
Definition: You can mix and match getStaticProps
, getServerSideProps
, and client-side fetching.
Important Point
This gives complete flexibility in how each page behaves, based on your data needs.
40. API Middleware (Advanced)
Definition: Use custom middleware functions in API routes.
// utils/auth.js
export function withAuth(handler) {
return async (req, res) => {
if (!req.headers.authorization) {
return res.status(401).json({ error: 'Unauthorized' });
}
return handler(req, res);
};
}
// pages/api/secret.js
import { withAuth } from '../../utils/auth';
export default withAuth((req, res) => {
res.status(200).json({ message: 'Secret data' });
});
Important Point
You can chain and reuse middleware functions in API routes for auth, logging, etc.
Conclusion
These extra points complete your cheatsheet. If you're serious about mastering Next.js, you need to understand routing deeply, pick the right data-fetching method per page, and optimize performance at both the build and runtime level. Don't blindly use SSR or SSG—know when and why to use each. Also, get comfortable with middleware, layouts, and the App Router (if you're using v13+). The framework is deep, but incredibly powerful when you wield it right.