Next.js
The React Framework for Production
Overview
Next.js is a full-stack React framework that enables you to build fast, user-friendly web applications. It provides:
- **File-based routing**: Create routes by adding files to the app directory - **Server Components**: Render components on the server for better performance - **API Routes**: Build API endpoints as part of your Next.js app - **Automatic code splitting**: Only load the code needed for each page - **Image optimization**: Automatic image optimization with the Image component - **Built-in CSS support**: Support for CSS Modules, Tailwind CSS, and more
Page Component (Server Component)
1// app/page.tsx2400">export 400">default 400">async 400">function 300">HomePage() {3 400">const data = 400">await 300">fetch('https://api.example.com/data');4 400">const posts = 400">await data.300">json();5 6 400">return (7 <main>8 <h1>Welcome to Next.js</h1>9 <ul>10 {posts.300">map((post) => (11 <li key={post.id}>{post.title}</li>12 ))}13 </ul>14 </main>15 );16}Installation
Quick Install
1-amber-400">npx create-next-app@latest my-appRequirements
- Node.js 18.17+
Setup Steps
- 1Run: npx create-next-app@latest my-app
- 2Answer the prompts (TypeScript: Yes, ESLint: Yes, Tailwind: Yes, App Router: Yes)
- 3Navigate to project: cd my-app
- 4Run development server: npm run dev
- 5Open http://localhost:3000
App Router
The App Router is Next.js's new routing system built on React Server Components. It enables:
- **Layouts**: Shared UI that preserves state across navigations - **Server Components**: Components that render on the server by default - **Streaming**: Progressive rendering with Suspense - **Data Fetching**: Simplified data fetching with async/await
Root Layout
1// app/layout.tsx2400">export 400">default 400">function 300">RootLayout({3 children,4}: {5 children: React.ReactNode;6}) {7 400">return (8 <html lang="en">9 <body>10 <nav>11 <a href="/">Home</a>12 <a href="/about">About</a>13 </nav>14 <main>{children}</main>15 <footer>ยฉ 2024</footer>16 </body>17 </html>18 );19}Server Components
Server Components allow you to render components on the server, reducing the JavaScript sent to the client. They can:
- Fetch data directly without useEffect - Access backend resources securely - Keep sensitive logic on the server
Use 'use client' directive for interactive components.
Server vs Client Components
1// Server Component (default)2// app/posts/page.tsx3400">import { db } 400">from '@/lib/db';4 5400">export 400">default 400">async 400">function 300">PostsPage() {6 400">const posts = 400">await db.posts.300">findMany();7 400">return <PostList posts={posts} />;8}9 10// Client Component11// components/LikeButton.tsx12'use client';13 14400">import { useState } 400">from 'react';15 16400">export 400">function 300">LikeButton({ postId }: { postId: 400">string }) {17 400">const [liked, setLiked] = 300">useState(400">false);18 19 400">return (20 <button onClick={() => 300">setLiked(!liked)}>21 {liked ? 'โค๏ธ' : '๐ค'}22 </button>23 );24}API Routes
API routes provide a way to build your API with Next.js. Any file inside the folder app/api is mapped to /api/* and will be treated as an API endpoint.
API Route Handler
1// app/api/users/route.ts2400">import { NextRequest, NextResponse } 400">from 'next/server';3 4400">export 400">async 400">function 300">GET(request: NextRequest) {5 400">const users = 400">await db.user.300">findMany();6 400">return NextResponse.300">json(users);7}8 9400">export 400">async 400">function 300">POST(request: NextRequest) {10 400">const body = 400">await request.300">json();11 400">const user = 400">await db.user.300">create({ data: body });12 400">return NextResponse.300">json(user, { status: 201 });13}Best Practices
- Use Server Components by default, Client Components for interactivity
- Implement proper loading.tsx and error.tsx for each route
- Use the Image component for automatic image optimization
- Implement ISR (Incremental Static Regeneration) for dynamic content
- Use generateStaticParams for dynamic routes at build time
- Implement proper metadata for SEO
- Use Server Actions for form handling
Common Pitfalls
Recommended File Structure
Code Snippets
Page Metadata
basicAdd SEO metadata to pages
1400">import type { Metadata } 400">from 'next';2 3400">export 400">const metadata: Metadata = {4 title: 'My Page Title',5 description: 'My page description',6 openGraph: {7 title: 'My Page Title',8 description: 'My page description',9 images: ['/og-image.jpg'],10 },11};Server Action
intermediateHandle form submissions with Server Actions
1// app/actions.ts2'use server';3 4400">import { revalidatePath } 400">from 'next/cache';5 6400">export 400">async 400">function 300">createPost(formData: FormData) {7 400">const title = formData.400">get('title') 400">as 400">string;8 400">const content = formData.400">get('content') 400">as 400">string;9 10 400">await db.post.300">create({11 data: { title, content }12 });13 14 300">revalidatePath('/posts');15}16 17// In component:18<form action={createPost}>19 <input name="title" />20 <textarea name="content" />21 <button type="submit">Create</button>22</form>