โ–ฒ

Next.js

๐Ÿ‘จโ€๐Ÿณ Chef

React for production

Next.js is the React framework for complete web applications.


Why Next.js

FeatureBenefit
Server ComponentsLess JavaScript to client
App RouterFolder-based routes
SSR/SSGSEO and performance
API RoutesIntegrated 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 })
}

Practice

โ†’ Blog with Next.js + MDX