공부공부/Next.js 공식문서

[next.js 공식문서] 11. Internationalization

고생쨩 2024. 2. 28. 08:03
728x90

next.js 13버전 때 학습내용 정리 문서로 현재와 다름 주의

Internationalization

Locale

  • ko-KR, en-US 등

개요

import { match } from '@formatjs/intl-localematcher';
import Negotiator from 'negotiator';
 
let headers = { 'Accept-Language': 'en-US,en;q=0.5' };
let languages = new Negotiator(headers).languages();
let locales = ['en-US', 'nl-NL', 'nl'];
let defaultLocale = 'en-US';
 
match(languages, locales, defaultLocale); // -> 'en-US'
import { NextResponse } from 'next/server'
 
let locales = ['en-US', 'nl-NL', 'nl']
 
// Get the preferred locale, similar to above or using a library
function getLocale(request) { ... }
 
export function middleware(request) {
  // Check if there is any supported locale in the pathname
  const pathname = request.nextUrl.pathname
  const pathnameIsMissingLocale = locales.every(
    (locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
  )
 
  // Redirect if there is no locale
  if (pathnameIsMissingLocale) {
    const locale = getLocale(request)
 
    // e.g. incoming request is /products
    // The new URL is now /en-US/products
    return NextResponse.redirect(
      new URL(`/${locale}/${pathname}`, request.url)
    )
  }
}
 
export const config = {
  matcher: [
    // Skip all internal paths (_next)
    '/((?!_next).*)',
    // Optional: only run on root (/) URL
    // '/'
  ],
}

middle 웨어와 라우팅을 app/[lang] 같이 구현

현지화

언어별 json등을 별도 생성하고

import 'server-only';
 
const dictionaries = {
  en: () => import('./dictionaries/en.json').then((module) => module.default),
  nl: () => import('./dictionaries/nl.json').then((module) => module.default),
};
 
export const getDictionary = async (locale) => dictionaries[locale]();
import { getDictionary } from './dictionaries';
 
export default async function Page({ params: { lang } }) {
  const dict = await getDictionary(lang); // en
  return <button>{dict.products.cart}</button>; // Add to Cart
}

위와 같이 사용

정적 생성

generateStaticParams를 사용하여 모든 페이지 또는 레이아웃과 같이 사용 가능

// app/[lang]/layout.js
export async function generateStaticParams() {
  return [{ lang: 'en-US' }, { lang: 'de' }];
}
 
export default function Root({ children, params }) {
  return (
    <html lang={params.lang}>
      <body>{children}</body>
    </html>
  );
}

이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.