โ–ฒ

Next.js

The React Framework for Production

v15.0.0IntermediateSSRSSGApp RouterServer ComponentsAPI Routes

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)

app/page.tsx
1// app/page.tsx
2400">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

Terminal
1-amber-400">npx create-next-app@latest my-app

Requirements

  • Node.js 18.17+

Setup Steps

  1. 1Run: npx create-next-app@latest my-app
  2. 2Answer the prompts (TypeScript: Yes, ESLint: Yes, Tailwind: Yes, App Router: Yes)
  3. 3Navigate to project: cd my-app
  4. 4Run development server: npm run dev
  5. 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

app/layout.tsx
1// app/layout.tsx
2400">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

Components.tsx
1// Server Component (default)
2// app/posts/page.tsx
3400">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 Component
11// components/LikeButton.tsx
12'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

app/api/users/route.ts
1// app/api/users/route.ts
2400">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

โš ๏ธUsing 'use client' unnecessarily
โš ๏ธNot handling loading and error states
โš ๏ธFetching data in Client Components when Server Components would work
โš ๏ธNot optimizing images with next/image
โš ๏ธIgnoring TypeScript errors

Recommended File Structure

Next.js Project
6 items
app
layout.tsx
page.tsx
loading.tsx
error.tsx
globals.css
api
users
route.ts
(dashboard)
layout.tsx
settings
page.tsx
components
ui
Header.tsx
lib
utils.ts
next.config.mjs
tailwind.config.ts
tsconfig.json

Code Snippets

Page Metadata

basic

Add SEO metadata to pages

TypeScript
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

intermediate

Handle form submissions with Server Actions

TypeScript
1// app/actions.ts
2'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>

Resources

Related Technologies