เมนู
ในหน้านี้

Internationalization (i18n)

สร้างระบบหลายภาษาด้วย dictionary-based translations และ locale routing

สำหรับ internationalization ผมใช้วิธี dictionary-based ด้วย JSON files สำหรับแต่ละภาษา รูปแบบนี้ทำงานได้ดีมากกับ Next.js App Router — locale ถูกตรวจจับจาก URL path (เช่น /en, /th, /zh) และโหลด dictionary ที่ถูกต้องฝั่ง server ผมเลือกวิธีนี้แทน i18next เพราะมันง่ายกว่า, type-safe ด้วย TypeScript และไม่ต้องการ dependencies เพิ่ม ฟังก์ชัน getDictionary ดึง translations ที่ถูกต้อง และ TypeScript ช่วยให้ไม่พลาด translation key ใดๆ

ผมใช้ dictionary-based approach เพราะความง่ายและ type-safety คุณสามารถใช้ next-intl, i18next, react-i18next หรือ Lingui สำหรับฟีเจอร์ขั้นสูงเช่น pluralization, interpolation หรือ translation management รูปแบบหลัก — การตรวจจับ locale จาก URL และโหลด translations ที่ถูกต้อง — ยังคงเหมือนกัน

วิธีการทำงาน

lib/
└── i18n/
    ├── config.ts             # Locale configuration
    ├── get-dictionary.ts     # Dictionary loader
    └── dictionaries/
        ├── en.json           # English translations
        ├── th.json           # Thai translations
        ├── th.json           # Thai translations

types/
└── dictionary.ts             # TypeScript types

proxy.ts                      # Next.js 16+ locale redirect
app/
└── [lang]/
    ├── layout.tsx            # Locale layout
    └── page.tsx              # Locale page

JSON Dictionaries

Store translations in JSON files for easy management and type-safety.

Middleware Redirect

Automatically redirect users to their preferred locale using middleware.

Type-Safe

Full TypeScript support with typed dictionary interface.

Server & Client

Works seamlessly with both Server and Client Components.

URL-Based Routing

Clean URLs with locale prefix (/en, /th) for SEO benefits.

Dynamic Import

Lazy load dictionaries to reduce initial bundle size.

คุณสมบัติหลัก

  • Dictionary-based translations (JSON files)
  • Dynamic locale routing (/th, /en, /zh)
  • Type-safe translations ด้วย TypeScript
  • SEO-friendly URL structure
  • ง่ายต่อการเพิ่มภาษาใหม่

ตัวอย่างการใช้งาน

เปลี่ยนภาษา

Hello, World!

Welcome to our application

Current State

Locale:en
URL:/en/page