logo

Juniverse Dev

Next JS에 i18n 다국어 적용하기

Next JS에 i18n 다국어 적용하기

Next JS 14 프로젝트에 next-intl 라이브러리를 사용해 i18n 다국어를 적용해보자

Next.js 14next-intl다국어i18n
282 views

Next Intl 공식 문서

next-intl이란?

Next.js 애플리케이션에서 다국어 지원을 쉽게 구현할 수 있도록 돕는 라이브러리로, Next JS 에서의 다국어 작업을 간편하게 만들어 준다. 

주요 기능은 다음과 같다.

 

적용 방법

설치

npm install next-intl

디렉토리 구조 (app 라우팅 기준)

└───app
│    ├───[locale]
│    │       page.tsx
│    │
├───messages
│       en.json
│       ko.json

Next JS 설정 파일에 플러그인 추가

// next.config.js
const createNextIntlPlugin = require('next-intl/plugin');

const withNextIntl = createNextIntlPlugin();

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: false,
};

module.exports = withNextIntl(nextConfig);

i18n.ts 설정 파일 추가

// i18n.ts

import { notFound } from 'next/navigation';
import { getRequestConfig } from 'next-intl/server';

// Can be imported from a shared config
const locales = ['en', 'ko', 'ja', 'zh'];

export default getRequestConfig(async ({ locale }) => {
  // Validate that the incoming `locale` parameter is valid
  if (!locales.includes(locale as any)) {
    notFound();
  }

  return {
    messages: (await import(`./messages/${locale}.json`)).default,
  };
});

middleware.ts 추가

import createMiddleware from 'next-intl/middleware';

export default createMiddleware({
  locales: ['en', 'ko', 'ja', 'zh'],
  defaultLocale: 'en',
});

export const config = {
  // Match only internationalized pathnames
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};

사용

CSR

export default function I18nTest = () => {
    const t = useTranslations();
    
    return <div>{t.test}<div>
}

SSR

export default async function Page({ params: { locale } }: DefaultPageProps) {
    const t = await getTranslations({ locale });
    
    return <div>{t.test}<div>
}