Next.js từ cơ bản đến nâng cao
Trang chủ / Module 12
🪟 Module 12 / 18 · 4 ngày 📅 Tuần 7 ●●●○ Khó

Routing nâng cao: parallel routes, intercepting routes, i18n

Parallel routes để render nhiều trang cùng lúc trong một layout, default.tsx, intercepting routes để mở modal có URL riêng, và đa ngôn ngữ với segment [locale].

@slot(..)interceptModal routei18n
📌 Vì sao module này quan trọng

Đây là những tính năng mà SPA phải tự dựng rất cực: modal ảnh có URL chia sẻ được (mở từ feed thì là modal, mở trực tiếp thì là trang), dashboard nhiều khu vực tải và lỗi độc lập, website đa ngôn ngữ có SEO đúng.

🎯 Mục tiêu học tập

  • Tạo parallel routes với slot @name và default.tsx
  • Render có điều kiện theo vai trò bằng slot
  • Làm modal route bằng intercepting route
  • Xây i18n với [locale], từ điển và generateStaticParams

Parallel routes

app/dashboard/
├─ layout.tsx          # nhận props: children, analytics, team
├─ page.tsx            # children
├─ @analytics/
│  ├─ page.tsx
│  ├─ loading.tsx      # mỗi slot có loading/error riêng
│  └─ default.tsx
└─ @team/
   ├─ page.tsx
   ├─ settings/page.tsx  # /dashboard/settings: slot team hiển thị settings
   └─ default.tsx
export default function DashboardLayout({ children, analytics, team }: LayoutProps<'/dashboard'>) {
  return (
    <div className="grid grid-cols-3 gap-4">
      <section className="col-span-2">{children}</section>
      <aside>{team}</aside>
      <section className="col-span-3">{analytics}</section>
    </div>
  );
}

Slot không thành một phần URL. Khi điều hướng mềm, slot không khớp URL mới giữ nguyên nội dung cũ; khi tải cứng (reload), Next.js render default.tsx cho slot không khớp — thiếu default.tsx thì 404 (Next.js 16 bắt buộc có default cho slot).

// Hiển thị theo vai trò
export default async function Layout({ admin, user }: { admin: React.ReactNode; user: React.ReactNode }) {
  const s = await verifySession();
  return s.role === 'admin' ? admin : user;
}

Intercepting routes: modal có URL

Mẫu kinh điển: bấm ảnh trong feed → mở modal với URL /photos/123; copy link gửi người khác hoặc reload → hiện trang đầy đủ.

app/
├─ layout.tsx               # render {children} và {modal}
├─ @modal/
│  ├─ default.tsx           # return null
│  └─ (.)photos/[id]/page.tsx   # chặn /photos/[id] khi điều hướng mềm từ cùng cấp -> modal
├─ feed/page.tsx
└─ photos/[id]/page.tsx     # trang đầy đủ khi vào trực tiếp
Ký hiệuChặn route ở
(.)cùng cấp
(..)cấp trên một bậc
(..)(..)trên hai bậc
(...)từ gốc app

(Các cấp tính theo route segment, không theo thư mục — slot @modal không tính là một cấp.)

// app/@modal/(.)photos/[id]/page.tsx
import { Modal } from '@/components/Modal';
export default async function PhotoModal({ params }: { params: Promise<{ id: string }> }) {
  const photo = await getPhoto((await params).id);
  return <Modal><img src={photo.url} alt={photo.alt} /></Modal>;
}

// components/Modal.tsx
'use client';
import { useRouter } from 'next/navigation';
export function Modal({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  return (
    <dialog open onClose={() => router.back()} onClick={e => e.target === e.currentTarget && router.back()}>
      {children}
      <button onClick={() => router.back()}>Đóng</button>
    </dialog>
  );
}

Đóng modal bằng router.back() để URL quay về feed. Điều hướng sang trang khác mà modal vẫn hiện → thêm @modal/[...catchAll]/page.tsx trả null (hoặc default.tsx đúng chỗ).

Đa ngôn ngữ

app/[locale]/
├─ layout.tsx      # <html lang={locale}>
├─ page.tsx
└─ dictionaries.ts
proxy.ts           # chuyển / -> /vi hoặc /en theo Accept-Language/cookie (Module 8)
// app/[locale]/dictionaries.ts
import 'server-only';
const dictionaries = {
  vi: () => import('./dictionaries/vi.json').then(m => m.default),
  en: () => import('./dictionaries/en.json').then(m => m.default),
};
export type Locale = keyof typeof dictionaries;
export const hasLocale = (l: string): l is Locale => l in dictionaries;
export const getDictionary = (l: Locale) => dictionaries[l]();
// app/[locale]/page.tsx
export async function generateStaticParams() { return [{ locale: 'vi' }, { locale: 'en' }]; }

export default async function Home({ params }: PageProps<'/[locale]'>) {
  const { locale } = await params;
  if (!hasLocale(locale)) notFound();
  const t = await getDictionary(locale);       // từ điển chỉ ở server, không vào bundle
  return <h1>{t.home.title}</h1>;
}

Thêm alternates.languages trong metadata cho hreflang. Thư viện đầy đủ (định dạng số/ngày, số nhiều, dùng ở client): next-intl.

🚩 Sai lầm hay gặp

  • Thiếu default.tsx cho slot → 404 khi reload.
  • Đóng modal bằng router.push('/feed') → lịch sử trình duyệt sai.
  • Gửi cả từ điển mọi ngôn ngữ xuống client.

🏋️ Bài tập thực hành

Gallery + dashboard + đa ngôn ngữ

(1) Feed ảnh với modal route, chia sẻ link được. (2) Dashboard 3 slot có loading/error riêng, một slot giả lập lỗi để thấy các slot khác vẫn chạy. (3) Toàn bộ site có /vi và /en, hreflang đúng.

📚 Tài nguyên học tập

✅ Tự đánh giá hoàn thành

  • Tôi giải thích được hành vi slot khi điều hướng mềm và khi reload
  • Tôi làm được modal route chia sẻ link được
  • Tôi dùng đúng ký hiệu (.), (..), (...)
  • Tôi xây được i18n với [locale]