Next.js
Next.js is the React framework for full-stack web applications, featuring the App Router, React Server Components (RSC), hybrid rendering, and static site generation.
App Router vs Legacy Pages Router
| Feature | App Router (app/) |
Legacy Pages Router (pages/) |
|---|---|---|
| Component Default | Server Components (RSC) | Client Components |
| Routing Mechanism | Directory structure (app/blog/[slug]/page.js) |
File structure (pages/blog/[slug].js) |
| Static Prerendering | generateStaticParams() |
getStaticPaths() + getStaticProps() |
| Layout System | Nested layout.js preserved across navigation |
Custom wrapper components in _app.js |
| Metadata API | export const metadata or generateMetadata() |
<Head> from next/head |
| Static HTML Export | output: 'export' in next.config.js |
next export (removed in Next.js 14) |
Server vs Client Components
Server Components (Default)
Components inside the app/ directory are React Server Components by default.
- Benefits: Zero bundle impact for server-side dependencies, direct database and filesystem access, secure API key handling, and faster initial page loads.
- Data Fetching: Async Server Components fetch data directly without lifecycle hooks:
// app/posts/page.js (Server Component)
export default async function PostsPage() {
const res = await fetch('https://api.example.com/posts', {
next: { revalidate: 3600 }, // Incremental Static Regeneration (ISR)
});
const posts = await res.json();
return (
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
Client Components ('use client')
Add 'use client' at the very top of a file when you need:
- React state and lifecycle hooks (
useState,useEffect,useReducer). - Browser event listeners (
onClick,onChange). - Browser APIs (
localStorage,window,navigator).
'use client';
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>Clicked: {count}</button>;
}
Static HTML Export (output: 'export')
For 100% statically hosted websites (e.g. GitHub Pages, AWS S3, Cloudflare Pages), configure static export in next.config.js:
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'export',
trailingSlash: true, // Emits /slug/index.html instead of /slug.html
};
module.exports = nextConfig;
Running next build writes static HTML, CSS, and JS assets directly to the out/ directory.
Prerendering Dynamic Routes (generateStaticParams)
When using static export with dynamic routes (app/[...slug]/page.js), declare all prerendered paths using generateStaticParams():
// app/[...slug]/page.js
import { getDocBySlug, getAllDocSlugs } from '@/lib/docs';
export async function generateStaticParams() {
const slugs = getAllDocSlugs();
return slugs.map((slug) => ({
slug: slug.split('/'),
}));
}
export default async function Page({ params }) {
const { slug } = await params;
const doc = getDocBySlug(slug.join('/'));
return (
<article>
<h1>{doc.title}</h1>
<div dangerouslySetInnerHTML={{ __html: doc.htmlContent }} />
</article>
);
}
Metadata & SEO
Export static or dynamic metadata objects directly from route files:
// Static metadata
export const metadata = {
title: 'HackingNote - Developer Documentation',
description: 'In-depth engineering notes, internals, and modern cheatsheets.',
openGraph: {
images: ['/og-banner.webp'],
},
};
// Dynamic metadata
export async function generateMetadata({ params }) {
const { slug } = await params;
const post = await fetchPost(slug);
return {
title: `${post.title} | HackingNote`,
description: post.excerpt,
};
}
Image & Font Optimization
next/image
Prevents layout shift (CLS) and serves modern formats (WebP/AVIF):
import Image from 'next/image';
import banner from '@/public/banner.webp';
// Local image: Dimensions inferred automatically
<Image src={banner} alt="Project Banner" placeholder="blur" />
// Remote image: Explicit width and height required
<Image src="https://example.com/photo.webp" alt="Avatar" width={80} height={80} />
next/font
Self-hosts Google Fonts or local fonts with zero runtime layout shift:
import { Inter, Roboto_Mono } from 'next/font/google';
export const inter = Inter({
subsets: ['latin'],
display: 'swap',
});

