next-intl
개요
next-intl은 Next.js App Router를 위한 선도적인 i18n 라이브러리입니다. 로케일 라우팅, 메시지 번역, 날짜/숫자 형식을 처리하며 서버 및 클라이언트 컴포넌트 모두와 호환됩니다. 복수형 및 변수를 위한 ICU 메시지 구문을 지원합니다.
지침
1단계: 설정
npm install next-intl
// i18n/request.ts — 로케일 감지
import { getRequestConfig } from 'next-intl/server'
export default getRequestConfig(async ({ requestLocale }) => {
const locale = await requestLocale || 'en'
return {
locale,
messages: (await import(`../messages/${locale}.json`)).default,
}
})
// messages/en.json
{
"HomePage": {
"title": "Welcome to {appName}",
"description": "The best tool for {count, plural, one {# team} other {# teams}}",
"cta": "Get Started"
},
"Dashboard": {
"greeting": "Hello, {name}",
"lastLogin": "Last login: {date, date, medium}"
}
}
// messages/de.json
{
"HomePage": {
"title": "Willkommen bei {appName}",
"description": "Das beste Tool für {count, plural, one {# Team} other {# Teams}}",
"cta": "Jetzt starten"
}
}
2단계: 서버 컴포넌트
// app/[locale]/page.tsx — 번역된 서버 컴포넌트
import { useTranslations } from 'next-intl'
export default function HomePage() {
const t = useTranslations('HomePage')
return (
<main>
<h1>{t('title', { appName: 'MyApp' })}</h1>
<p>{t('description', { count: 5000 })}</p>
<a href="/signup">{t('cta')}</a>
</main>
)
}
3단계: 미들웨어 라우팅
// middleware.ts — 로케일 라우팅
import createMiddleware from 'next-intl/middleware'
export default createMiddleware({
locales: ['en', 'de', 'fr', 'ja'],
defaultLocale: 'en',
localePrefix: 'as-needed', // /de/about 이지만 /about (en의 경우)
})
export const config = { matcher: ['/((?!api|_next|.*\\..*).*)'] }
가이드라인
- ICU 메시지 구문: 복수형의 경우
{count, plural, one {# item} other {# items}}를 사용합니다. - 서버 컴포넌트: 컨텍스트 없이
useTranslations()를 직접 사용합니다. - 클라이언트 컴포넌트:
NextIntlClientProvider로 감쌉니다. - 유지보수를 위해 메시지 키를 페이지/컴포넌트별로 네임스페이스화합니다.
- 기본 로케일에
/en접두사를 피하려면localePrefix: 'as-needed'를 사용합니다.