글쓰는 개발자

[nextjs] App Router 다국어 지원 i18n next-intl 본문

Development/IT 튜토리얼

[nextjs] App Router 다국어 지원 i18n next-intl

세가사 2024. 7. 30. 07:34
반응형

기존 react 단일사용을 할 때는 react-localization을 사용해서 영문 국문 프로파일을 나누고 이를 불러서 사용하면 브라우저 언어를 인지해서 영문 국문을 자동으로 구분해서 출력해주었다.

 

nextjs에서 해당 방법을 사용하면 충돌이 발생해서 next js에 맞는 방식의 다국어 지원방법을 찾아야 한다.

 

nextjs에는 App Router를 사용한 다국어 지원 방식을 제공하는데 도메인 뒤에 kr 이나 en을 붙이면 해당 언어로된 홈페이지가 보여지는 방식이다.

 

사용방식은 매번 업데이트 되기 때문에 만약 아래 글을 따라했는데 동작을 하지 않는다면 해당 링크를 참고해보자.

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

 

Next.js internationalization (i18n) – Internationalization (i18n) for Next.js

 

next-intl-docs.vercel.app

 

먼저 nextjs 앱에 필요한 라이브러리를 설치한다.

npm install next-intl

 

그리고 다음과 같은 폴더 구조를 만들어야 한다.

├── messages (1)
│   ├── en.json
│   └── ...
├── next.config.js (2)
└── src
    ├── i18n.ts (3)
    ├── middleware.ts (4)
    └── app
        └── [locale]
            ├── layout.tsx (5)
            └── page.tsx (6)

 

공식 페이지에서는 next.config.js가 next.config.mjs로 되어있었는데 mjs를 사용하려면 추가적인 구성이 필요한것 같아서 필자는 next.config.js를 사용해서 구성했다.

이때 주의할 점은 기존의 layout.tsx와 page.tsx를 [locale] 이라는 괄호로 이루어진 폴더를 만들어 넣어주어야 한다는 것이다.

 

이제 각 파일들을 다음과 같이 구성해보자.

[1] messages/en.json

{
  "HomePage": {
    "title": "Hello world!"
  }
}

 

[2] next.config.js

const createNextIntlPlugin = require('next-intl/plugin');
 
const withNextIntl = createNextIntlPlugin();
 
/** @type {import('next').NextConfig} */
const nextConfig = {};
 
module.exports = withNextIntl(nextConfig);

 

[3] i18n.ts

import {notFound} from 'next/navigation';
import {getRequestConfig} from 'next-intl/server';
 
// Can be imported from a shared config
const locales = ['ko', 'en'];
 
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
  };
});

 

[4] middleware.ts

import createMiddleware from 'next-intl/middleware';
 
export default createMiddleware({
  // A list of all locales that are supported
  locales: ['ko', 'en'],
 
  // Used when no locale matches
  defaultLocale: 'ko'
});
 
export const config = {
  // Match only internationalized pathnames
  matcher: ['/', '/(ko|en)/:path*']
};

 

[5] app/[locale]/layout.tsx

import {NextIntlClientProvider} from 'next-intl';
import {getMessages} from 'next-intl/server';
 
export default async function LocaleLayout({
  children,
  params: {locale}
}: {
  children: React.ReactNode;
  params: {locale: string};
}) {
  // Providing all messages to the client
  // side is the easiest way to get started
  const messages = await getMessages();
 
  return (
    <html lang={locale}>
      <body>
        <NextIntlClientProvider messages={messages}>
          {children}
        </NextIntlClientProvider>
      </body>
    </html>
  );
}

 

[6] app/[locale]/page.tsx

import {useTranslations} from 'next-intl';
 
export default function HomePage() {
  const t = useTranslations('HomePage');
  return <h1>{t('title')}</h1>;
}

 

설정을 완료하면 domain/ko나 domain/en으로 제대로 동작하는지 확인해보자.

반응형

'Development > IT 튜토리얼' 카테고리의 다른 글

도커 MySQL 설치  (0) 2024.04.13
윈도우 도커(Docker) 설치  (0) 2024.04.13