Next.js Guide
react
nextjs
server-side rendering
static site generation
Installation
npx create-next-app@latest
# or
yarn create next-app
# or
pnpm create next-app
File-based Routing
pages/index.js
→/
pages/about.js
→/about
pages/blog/[slug].js
→/blog/:slug
Dynamic Routes
// pages/posts/[id].js
import { useRouter } from 'next/router'
export default function Post() {
const router = useRouter()
const { id } = router.query
return <p>Post: {id}</p>
}
Link Component
import Link from 'next/link'
function Home() {
return (
<ul>
<li>
<Link href="/">Home</Link>
</li>
<li>
<Link href="/about">About Us</Link>
</li>
<li>
<Link href="/blog/hello-world">Blog Post</Link>
</li>
</ul>
)
}
Image Component
import Image from 'next/image'
function Avatar() {
return <Image src="/me.png" alt="me" width="64" height="64" />
}
API Routes
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ name: 'John Doe' })
}
getServerSideProps (Server-Side Rendering)
export async function getServerSideProps(context) {
const res = await fetch(`https://api.example.com/data`)
const data = await res.json()
return {
props: { data }, // will be passed to the page component as props
}
}
getStaticProps (Static Site Generation)
export async function getStaticProps(context) {
const res = await fetch(`https://api.example.com/data`)
const data = await res.json()
return {
props: { data }, // will be passed to the page component as props
revalidate: 60, // In seconds
}
}
getStaticPaths (for Dynamic Routes)
export async function getStaticPaths() {
const res = await fetch('https://api.example.com/posts')
const posts = await res.json()
const paths = posts.map((post) => ({
params: { id: post.id },
}))
return { paths, fallback: false }
}
Custom App
// pages/_app.js
import '../styles/globals.css'
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp
Custom Document
// pages/_document.js
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
Environment Variables
.env.local
for local environment variables- Use
process.env.NEXT_PUBLIC_VARIABLE_NAME
for client-side variables
CSS Modules
// styles/Home.module.css
.container {
padding: 0 2rem;
}
// pages/index.js
import styles from '../styles/Home.module.css'
export default function Home() {
return <div className={styles.container}>Hello Next.js!</div>
}
Remember, Next.js is constantly evolving. Always refer to the official Next.js documentation for the most up-to-date information and best practices.