Next.js
Updated: September 10, 2025Categories: Language, Web, Frontend, Framework
Printed from:
Next.js Cheatsheet
1. Installation and Setup
Create a New Next.js Project
Bash
123456789# Using npx
npx create-next-app@latest my-next-app
# Using yarn
yarn create next-app my-next-app
# Using TypeScript
npx create-next-app@latest my-next-app --typescript
Project Initialization Options
JSON
123456789101112{
"name": "my-next-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
}
}
2. Project Structure
my-next-app/
│
├── pages/
│ ├── index.tsx
│ ├── _app.tsx
│ ├── _document.tsx
│ └── api/
│ └── hello.ts
│
├── public/
│ ├── favicon.ico
│ └── images/
│
├── components/
│ ├── Layout.tsx
│ └── Header.tsx
│
├── styles/
│ ├── globals.css
│ └── Home.module.css
│
├── lib/
│ └── utils.ts
│
└── next.config.js
3. Routing
Basic File-Based Routing
TypeScript
12345678910// pages/index.tsx
export default function Home() {
return <h1>Home Page</h1>
}
// pages/about.tsx
export default function About() {
return <h1>About Page</h1>
}
Dynamic Routes
TypeScript
12345678910111213141516171819// pages/posts/[id].tsx
import { useRouter } from 'next/router'
export default function Post() {
const router = useRouter()
const { id } = router.query
return <h1>Post: {id}</h1>
}
// Catch-all routes
// pages/posts/[...slug].tsx
export default function Post() {
const router = useRouter()
const { slug } = router.query
return <h1>Post Slug: {slug?.join('/')}</h1>
}
Nested Routes
pages/
└── blog/
├── index.tsx
└── [slug].tsx
4. Pages and Components
Page Component
TypeScript
123456789// pages/index.tsx
import type { NextPage } from 'next'
const Home: NextPage = () => {
return <div>Welcome to Next.js!</div>
}
export default Home
Custom App Component
TypeScript
12345678910// pages/_app.tsx
import type { AppProps } from 'next/app'
import '../styles/globals.css'
function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
export default MyApp
Custom Document
TypeScript
12345678910111213// pages/_document.tsx
import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document {
render() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
5. Data Fetching
Static Site Generation (SSG)
TypeScript
123456789101112131415161718// pages/posts/[id].tsx
export async function getStaticPaths() {
const posts = await fetchPosts()
const paths = posts.map((post) => ({
params: { id: post.id.toString() }
}))
return { paths, fallback: false }
}
export async function getStaticProps({ params }) {
const post = await fetchPostById(params.id)
return {
props: { post },
revalidate: 60 // Incremental Static Regeneration
}
}
Server-Side Rendering (SSR)
TypeScript
12345678910// pages/posts/[id].tsx
export async function getServerSideProps(context) {
const { id } = context.params
const post = await fetchPostById(id)
return {
props: { post }
}
}
Client-Side Data Fetching with SWR
TypeScript
1234567891011import useSWR from 'swr'
function Profile() {
const { data, error } = useSWR('/api/user', fetcher)
if (error) return <div>Failed to load</div>
if (!data) return <div>Loading...</div>
return <div>Hello {data.name}!</div>
}
6. API Routes
Creating API Endpoints
TypeScript
1234567891011// pages/api/users.ts
import type { NextApiRequest, NextApiResponse } from 'next'
export default function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === 'GET') {
res.status(200).json({ users: ['John', 'Jane'] })
} else {
res.status(405).end()
}
}
API Route Middleware
TypeScript
12345678910export default function handler(
req: NextApiRequest,
res: NextApiResponse
) {
// Middleware-like logic
if (!req.headers.authorization) {
return res.status(401).json({ error: 'Unauthorized' })
}
// Actual route logic
res.status(200).json({ message: 'Success' })
}
7. Styling
CSS Modules
TypeScript
12345678910111213// components/Button.module.css
.error {
background: red;
color: white;
}
// components/Button.tsx
import styles from './Button.module.css'
export default function Button() {
return <button className={styles.error}>Error Button</button>
}
Tailwind CSS Integration
Bash
123npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p
TypeScript
12345678910// tailwind.config.js
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
theme: { extend: {} },
plugins: [],
}
8. Image Optimization
TypeScript
12345678import Image from 'next/image'
function ProfilePicture() {
return (
<Image
src="/profile.jpg"
alt="Profile Picture"
width={500}
height={500}
layout="responsive"
priority
/>
)
}
9. Performance Optimization
Dynamic Imports
TypeScript
1234567import dynamic from 'next/dynamic'
const DynamicComponent = dynamic(() => import('../components/HelloWorld'), {
loading: () => <p>Loading...</p>,
ssr: false
})
10. Deployment
Vercel Deployment
Bash
123456# Install Vercel CLI
npm i -g vercel
# Deploy
vercel
Static Export
Bash
123next build
next export
11. Configuration
next.config.js
JavaScript
1234567891011121314module.exports = {
reactStrictMode: true,
env: {
CUSTOM_KEY: process.env.CUSTOM_KEY
},
redirects: async () => [
{
source: '/old-path',
destination: '/new-path',
permanent: true
}
]
}
12. TypeScript Integration
Basic TypeScript Setup
TypeScript
123456789101112import type { NextPage } from 'next'
import type { ReactElement } from 'react'
const Home: NextPage = () => {
return <div>Home Page</div>
}
// Layout with TypeScript
function Layout({ children }: { children: ReactElement }) {
return <div>{children}</div>
}
13. Common Hooks and Utilities
useRouter
TypeScript
123456789101112import { useRouter } from 'next/router'
function MyComponent() {
const router = useRouter()
const handleClick = () => {
router.push('/dashboard')
}
return <button onClick={handleClick}>Go to Dashboard</button>
}
Head Component
TypeScript
12345678import Head from 'next/head'
function MyPage() {
return (
<>
<Head>
<title>My Page Title</title>
<meta name="description" content="Page description" />
<link rel="icon" href="/favicon.ico" />
</Head>
{/* Page content */}
</>
)
}
14. Build and Development Commands
Bash
12345678910111213141516# Development Server
npm run dev
yarn dev
# Production Build
npm run build
yarn build
# Start Production Server
npm run start
yarn start
# Lint Code
npm run lint
yarn lint
15. Best Practices and Common Patterns
- Use
getStaticPropsfor static content - Leverage Incremental Static Regeneration (ISR)
- Implement dynamic imports for large components
- Use CSS Modules for component-level styling
- Optimize images with
next/image - Use TypeScript for type safety
- Implement proper error handling in API routes
- Use environment variables for configuration
- Minimize client-side JavaScript
- Implement proper SEO with
next/head
Pro Tip: Always keep your Next.js and dependencies updated to leverage the latest features and performance improvements.
Continue Learning
Discover more cheatsheets to boost your productivity