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