React for production
Next.js is the React framework for complete web applications.
Why Next.js
| Feature | Benefit |
|---|---|
| Server Components | Less JavaScript to client |
| App Router | Folder-based routes |
| SSR/SSG | SEO and performance |
| API Routes | Integrated backend |
Installation
npx create-next-app@latest my-app --typescript --tailwind --app
cd my-app
npm run dev
Folder structure
app/
โโโ layout.tsx # Global layout
โโโ page.tsx # Page /
โโโ about/
โ โโโ page.tsx # Page /about
โโโ api/
โ โโโ hello/
โ โโโ route.ts # API endpoint
โโโ [slug]/
โโโ page.tsx # Dynamic route
Server vs Client Components
// Server Component (default)
async function ProductList() {
const products = await db.products.findMany()
return <ul>{products.map(p => <li key={p.id}>{p.name}</li>)}</ul>
}
// Client Component
'use client'
function Counter() {
const [count, setCount] = useState(0)
return <button onClick={() => setCount(count + 1)}>{count}</button>
}
API Routes
// app/api/users/route.ts
import { NextResponse } from 'next/server'
export async function GET() {
return NextResponse.json({ users: [] })
}
export async function POST(request: Request) {
const body = await request.json()
return NextResponse.json({ created: body })
}