const locale = window.navigator.language
navigator.language는 유저가 사용중인 브라우저 UI를 저장하고 브라우저가 직접 세팅한다. UTS Locale Identifiers 형식의 string을 반환한다.
사용자가 웹에 접근했을 때 요청하는 HTTP의 Accept-Language 헤더에 기반하여 감지한다.
[locale]
폴더 안에 위치설치: npm install next-intl
파일 구조
├── messages (1)
│ ├── en.json
│ └── ...
├── middleware.ts (2)
└── app
└── [locale]
├── layout.tsx (3)
└── page.tsx (4)
{
"Index": {
"title": "Hello world!"
}
}
import createMiddleware from 'next-intl/middleware';
export default createMiddleware({
// A list of all locales that are supported
locales: ['en', 'de'],
// If this locale is matched, pathnames work without a prefix (e.g. `/about`)
defaultLocale: 'en'
});
export const config = {
// Skip all paths that should not be internationalized. This example skips the
// folders "api", "_next" and all files with an extension (e.g. favicon.ico)
matcher: ['/((?!api|_next|.*\\..*).*)']
};
NextIntlClientProvider
를 넣어준다.import {NextIntlClientProvider} from 'next-intl';
import {notFound} from 'next/navigation';
export function generateStaticParams() {
return [{locale: 'en'}, {locale: 'de'}];
}
export default async function LocaleLayout({children, params: {locale}}) {
let messages;
try {
messages = (await import(`../../messages/${locale}.json`)).default;
} catch (error) {
notFound();
}
return (
<html lang={locale}>
<body>
<NextIntlClientProvider locale={locale} messages={messages}>
{children}
</NextIntlClientProvider>
</body>
</html>
);
}
'use client';
import {useTranslations} from 'next-intl';
export default function Index() {
const t = useTranslations('Index');
return <h1>{t('title')}</h1>;
}
상단 클라이언트 컴포넌트 설정의 1, 2, 4번은 동일함
import {getRequestConfig} from 'next-intl/server';
export default getRequestConfig(async ({locale}) => ({
messages: (await import(`./messages/${locale}.json`)).default
}));
const withNextIntl = require('next-intl/plugin')(
// This is the default (also the `src` folder is supported out of the box)
'./i18n.ts'
);
module.exports = withNextIntl({
// Other Next.js configuration ...
});
import {useLocale} from 'next-intl';
import {notFound} from 'next/navigation';
export default function LocaleLayout({children, params}) {
const locale = useLocale();
// Show a 404 error if the user requests an unknown locale
if (params.locale !== locale) {
notFound();
}
return (
<html lang={locale}>
<body>{children}</body>
</html>
);
}
정적 렌더링 할 경우, 1) 클라이언트 컴포넌트 처리 방식 2) 외부 컴포넌트에서 API를 가져오는 방식 3) CDN 캐싱을 통한 방식을 권장함