blog.dopana

Back

Next.js là React framework phổ biến nhất cho production. App Router (2023) thay đổi cách tổ chức code hoàn toàn.

App Router vs Pages Router#

Pages RouterApp Router
File-based routingFile-based routing + layout
_app.tsx globallayout.tsx per segment
getServerSidePropsServer Components (mặc định)
Client Components khi cần'use client' khi cần
API routes riêngServer Actions + Route Handlers

Cấu Trúc Project#

Server Components — Mặc Định#

Lợi ích: Direct database access, không bundle JS cho server code, nhỏ hơn, nhanh hơn.

Client Components — Khi Cần Tương Tác#

Nguyên tắc: Server Component mặc định, chỉ thêm 'use client' khi cần state, effect, event handler.

Server Actions — Không Cần API Route#

// Component
export function PostForm() {
  return (
    <form action={createPost}>
      <input name="title" required minLength={3} />
      <textarea name="content" required />
      <button type="submit">Create Post</button>
    </form>
  );
}
tsx

Không cần API route — logic chạy trên server, an toàn, type-safe.

Data Fetching & Caching#

Middleware — Bảo Vệ Route#

Image Optimization#

import Image from 'next/image';

export default function Profile({ user }: { user: User }) {
  return (
    <Image
      src={user.avatar}
      alt={user.name}
      width={300}
      height={300}
      priority={true}        // Above the fold
      placeholder="blur"     // Blur placeholder
      blurDataURL="data:..." // Base64 blur
    />
  );
}
tsx

Next.js tự động: WebP, responsive sizes, lazy loading, preload priority images.

Metadata & SEO#

Performance Checklist#

  • Server Components mặc định
  • next/image cho tất cả images
  • next/link cho client-side navigation
  • Streaming với loading.tsxSuspense
  • ISR cho content pages
  • Static rendering cho public pages
  • next/font — tối ưu font (không render-blocking)
  • Bundle analyzer — kiểm tra kích thước
  • Analytics — Web Vitals tracking

Deploy#

Kết Luận#

Next.js App Router là tương lai của React. Server Components + Server Actions giảm đáng kể JavaScript bundle. ISR cho content site, dynamic cho personalized pages. Middleware cho auth và redirects. Deploy lên Vercel hoặc Docker.

Tài liệu tham khảo#