What is Next.js?
Next.js is a React framework created by Vercel that enables server-side rendering (SSR), static site generation (SSG), and full-stack capabilities out of the box. It's one of the most popular frameworks for building production React applications.
Key Features
| Feature | Description |
|---|---|
| File-based Routing | Pages defined by file structure |
| Server Components | React components that run on server |
| SSR/SSG/ISR | Multiple rendering strategies |
| API Routes | Backend endpoints in same project |
| Image Optimization | Automatic image optimization |
| TypeScript | First-class TypeScript support |
Rendering Strategies
1. Server-Side Rendering (SSR)
Page rendered on each request:
// app/products/[id]/page.tsx
async function ProductPage({ params }) {
const product = await fetch(`/api/products/${params.id}`);
return <ProductDetail product={product} />;
}
2. Static Site Generation (SSG)
Page rendered at build time:
// Next.js 13+ with generateStaticParams
export async function generateStaticParams() {
const products = await getProducts();
return products.map(p => ({ id: p.id }));
}
3. Incremental Static Regeneration (ISR)
Static pages that revalidate periodically:
// Revalidate every 60 seconds
export const revalidate = 60;
App Router (Next.js 13+)
The new App Router uses React Server Components:
app/
βββ layout.tsx # Root layout
βββ page.tsx # Home page (/)
βββ about/
β βββ page.tsx # About page (/about)
βββ blog/
β βββ page.tsx # Blog list (/blog)
β βββ [slug]/
β βββ page.tsx # Blog post (/blog/my-post)
βββ api/
βββ users/
βββ route.ts # API endpoint (/api/users)
Server Actions
Handle form submissions without API routes:
async function createPost(formData: FormData) {
"use server";
const title = formData.get("title");
await db.posts.create({ title });
revalidatePath("/posts");
}
export default function NewPost() {
return (
<form action={createPost}>
<input name="title" />
<button type="submit">Create</button>
</form>
);
}
API Routes
// app/api/users/route.ts
import { NextResponse } from "next/server";
export async function GET() {
const users = await db.users.findMany();
return NextResponse.json(users);
}
export async function POST(request: Request) {
const body = await request.json();
const user = await db.users.create(body);
return NextResponse.json(user, { status: 201 });
}
Next.js vs SvelteKit
| Aspect | Next.js | SvelteKit |
|---|---|---|
| Framework | React | Svelte |
| Bundle size | Larger | Smaller |
| Learning curve | Moderate | Lower |
| Ecosystem | Massive | Growing |
| Performance | Good | Excellent |
When to Use Next.js
β
React ecosystem preference
β
SEO-critical applications
β
E-commerce, marketing sites
β
Full-stack applications
β
Large team / hiring pool