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 })
}