본문 바로가기
개인공부

Next.js Docs (14) Internationalization

by 강물둘기 2023. 7. 19.

Internationalization(국제화)

Next.js 를 사용하면 여러 언어를 지원하도록 컨텐츠의 라우팅과 렌더링을 구성할 수 있다. 웹사이트가 다른 여러 지역 적응할 수 있도록 하려면 번역된 컨텐츠를 포함하고, 국제화(internationalization) route를 포함시킨다.

 

Terminology(용어)

- Locale : 언어 및 서식 설정 집합에 대한 식별자이다. 여기에는 일반적으로 사용자가 선호하는 언어와 지리적 지역이 포함된다.

    - en-US : 미국에서 사용되는 영어

    - nl - NL : 네덜란드에서 사용되는 네덜란드어

    - nl : 일반적인 네덜란드어

 

 

Routing Overview( 라우팅 개요 )

브라우저에서 사용자의 언어 환경설정을 사용하여 사용할 Locale을 선택하는 것이 좋다. 선호하는 언어를 변경하면 애플리케이션으로 들어오는 Accept-Language 헤더가 수정된다.

 

예를 들어, 다음 라이브러리를 사용해서 들어오는 Request를 확인하여 헤더, 지원할 Locale, 기본 Locale을 기준으로 선택할 Locale을 결정할 수 있다.

// middleware.js

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'

 

라우팅은 하위 경로( /fr/products) 또는 도메인( my-site.fr/products)으로 국제화 할 수 있다. 이 정보를 사용하여 미들웨어 내부의 Locale을 기준으로 사용자를 redirect 할 수 있다.

// middleware.js

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
    // '/'
  ],
}

 

마지막으로 app/ 안의 특수 파일들이 app/[lang] 아래에 중첩되어 있는지 확인한다. 이렇게 하면 Next.js 라우터가 route의 다른 locale을 동적으로 처리하고, lang 매개변수를 모든 레이아웃과 페이지로 전달할 수 있다. 예시 :

// app/[lang]/page.js

// You now have access to the current locale
// e.g. /en-US/products -> `lang` is "en-US"
export default async function Page({ params: { lang } }) {
  return ...
}

 

루트 레이아웃은 새 폴더(예 : app/[lang]/layout.js)에 중첩될 수도 있다.

 

 

Localization(현지화)

사용자가 선호하는 locale 또는 현지화에 따라 표시되는 내용을 변경하는 것은 Next.js에 국한된 것이 아니다. 아래에 설명된 패턴은 모든 웹 애플리케이션에서 동일하게 작동한다.

 

애플리케이션 내에서 영어와 네덜란드어 컨텐츠를 모두 지원한다고 가정해보자. 일부 키에서 현지화된 문자열로의 매핑을 제공하는 두 개의 다른 "사전"을 유지할 수 있다. 예시 :

// dictionaries/en.json
{
  "products": {
    "cart": "Add to Cart"
  }
}
// dictionaries/nl.json

{
  "products": {
    "cart": "Toevoegen aan Winkelwagen"
  }
}

 

그런 다음 getDictionary 함수를 만들어 요청된 Locale에 대한 변환을 불러올 수 있다.

// app/[lang]/dictionaries.js

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]()

 

현재 선택된 언어가 주어지면 레이아웃이나 페이지 내에서 사전을 가져올 수 있다.

// app/[lang]/page.js

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
}

 

app/ 디렉토리의 모든 레이아웃과 페이지는 기본적으로 서버 컴포넌트로 설정되므로 클라이언트 측 JavaScript 번들 크기에 영향을 미치는 변환 파일의 크기에 대해 걱정할 필요가 없다. 이 코드는 서버에서만 실행되고 결과 HTML만 브라우저로 전송된다.

 

 

Static Generation(정적 생성)

지정된 locale 집합에 대한 정적 경로를 생성하려면 generateStaticParams를 아무 페이지나 레이아웃에서 사용하면 된다. 예를 들어 root 레이아웃에서는 global 일 수도 있다 :

// 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>
  )
}

 

Examples

- https://github.com/vercel/next.js/tree/canary/examples/app-dir-i18n-routing

- https://next-intl-docs.vercel.app/docs/getting-started

 

 

Reference

- https://nextjs.org/docs/app/building-your-application/routing/internationalization

 

Routing: Internationalization | Next.js

Using App Router Features available in /app

nextjs.org

 

 

댓글