Files
sam-react-prod/claudedocs/guides/[IMPL-2025-11-06] i18n-usage-guide.md
byeongcheolryu 65a8510c0b fix: 품목기준관리 실시간 동기화 수정
- BOM 항목 추가/수정/삭제 시 섹션탭 즉시 반영
- 섹션 복제 시 UI 즉시 업데이트 (null vs undefined 이슈 해결)
- 항목 수정 기능 추가 (useTemplateManagement)
- 실시간 동기화 문서 추가

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-27 22:19:50 +09:00

16 KiB

next-intl 다국어 설정 가이드

개요

이 문서는 Next.js 16 기반 멀티 테넌트 ERP 시스템의 다국어(i18n) 설정 및 사용법을 설명합니다. next-intl 라이브러리를 활용하여 한국어(ko), 영어(en), 일본어(ja) 3개 언어를 지원합니다.


📦 설치된 패키지

{
  "dependencies": {
    "next-intl": "^latest"
  }
}

🏗️ 프로젝트 구조

src/
├── i18n/
│   ├── config.ts                # i18n 설정 (지원 언어, 기본 언어)
│   └── request.ts               # 서버사이드 메시지 로딩
├── messages/
│   ├── ko.json                  # 한국어 메시지
│   ├── en.json                  # 영어 메시지
│   └── ja.json                  # 일본어 메시지
├── app/
│   └── [locale]/                # 동적 로케일 라우팅
│       ├── layout.tsx           # 루트 레이아웃 (NextIntlClientProvider)
│       └── page.tsx             # 홈 페이지
├── components/
│   ├── LanguageSwitcher.tsx     # 언어 전환 컴포넌트
│   ├── WelcomeMessage.tsx       # 번역 샘플 컴포넌트
│   └── NavigationMenu.tsx       # 내비게이션 메뉴 컴포넌트
└── middleware.ts                # 로케일 감지 + 봇 차단 미들웨어

🔧 핵심 설정 파일

1. i18n 설정 (src/i18n/config.ts)

export const locales = ['ko', 'en', 'ja'] as const;
export type Locale = (typeof locales)[number];

export const defaultLocale: Locale = 'ko';

export const localeNames: Record<Locale, string> = {
  ko: '한국어',
  en: 'English',
  ja: '日本語',
};

export const localeFlags: Record<Locale, string> = {
  ko: '🇰🇷',
  en: '🇺🇸',
  ja: '🇯🇵',
};

주요 설정:

  • locales: 지원하는 언어 목록
  • defaultLocale: 기본 언어 (한국어)
  • localeNames: 언어 표시 이름
  • localeFlags: 언어별 국기 이모지

2. 메시지 로딩 (src/i18n/request.ts)

import { getRequestConfig } from 'next-intl/server';
import { locales } from './config';

export default getRequestConfig(async ({ requestLocale }) => {
  let locale = await requestLocale;

  if (!locale || !locales.includes(locale as any)) {
    locale = 'ko'; // 기본값
  }

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

동작 방식:

  • 요청된 로케일을 확인
  • 유효하지 않으면 기본 언어(ko)로 폴백
  • 해당 언어의 메시지 파일을 동적으로 로드

3. Next.js 설정 (next.config.ts)

import createNextIntlPlugin from 'next-intl/plugin';

const withNextIntl = createNextIntlPlugin('./src/i18n/request.ts');

const nextConfig: NextConfig = {
  /* config options here */
};

export default withNextIntl(nextConfig);

역할: next-intl 플러그인을 Next.js에 통합


4. 미들웨어 (src/middleware.ts)

import createMiddleware from 'next-intl/middleware';
import { locales, defaultLocale } from '@/i18n/config';

const intlMiddleware = createMiddleware({
  locales,
  defaultLocale,
  localePrefix: 'as-needed', // 기본 언어는 URL에 표시하지 않음
});

export function middleware(request: NextRequest) {
  // ... 봇 차단 로직 ...

  // i18n 미들웨어 실행
  const intlResponse = intlMiddleware(request);

  // 보안 헤더 추가
  intlResponse.headers.set('X-Robots-Tag', 'noindex, nofollow');

  return intlResponse;
}

특징:

  • 자동 로케일 감지 (Accept-Language 헤더 기반)
  • URL 리다이렉션 처리 (예: //ko)
  • 기존 봇 차단 로직과 통합

5. 루트 레이아웃 (src/app/[locale]/layout.tsx)

import { NextIntlClientProvider } from 'next-intl';
import { getMessages } from 'next-intl/server';
import { notFound } from 'next/navigation';
import { locales } from '@/i18n/config';

export function generateStaticParams() {
  return locales.map((locale) => ({ locale }));
}

export default async function RootLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;

  if (!locales.includes(locale as any)) {
    notFound();
  }

  const messages = await getMessages();

  return (
    <html lang={locale}>
      <body>
        <NextIntlClientProvider messages={messages}>
          {children}
        </NextIntlClientProvider>
      </body>
    </html>
  );
}

주요 기능:

  • generateStaticParams: 정적 생성할 로케일 목록 반환
  • NextIntlClientProvider: 클라이언트 컴포넌트에서 번역 사용 가능
  • 로케일 유효성 검증

📝 메시지 파일 구조

메시지 파일 예시 (src/messages/ko.json)

{
  "common": {
    "appName": "ERP 시스템",
    "welcome": "환영합니다",
    "loading": "로딩 중...",
    "save": "저장",
    "cancel": "취소"
  },
  "auth": {
    "login": "로그인",
    "email": "이메일",
    "password": "비밀번호"
  },
  "navigation": {
    "dashboard": "대시보드",
    "inventory": "재고관리",
    "finance": "재무관리"
  },
  "validation": {
    "required": "필수 항목입니다",
    "invalidEmail": "유효한 이메일 주소를 입력하세요",
    "minLength": "최소 {min}자 이상 입력하세요"
  }
}

네임스페이스 구조:

  • common: 공통 UI 요소
  • auth: 인증 관련
  • navigation: 메뉴/내비게이션
  • validation: 유효성 검증 메시지

💻 컴포넌트에서 사용법

1. 클라이언트 컴포넌트에서 사용

기본 사용법

'use client';

import { useTranslations } from 'next-intl';

export default function MyComponent() {
  const t = useTranslations('common');

  return (
    <div>
      <h1>{t('welcome')}</h1>
      <p>{t('appName')}</p>
    </div>
  );
}

여러 네임스페이스 사용

'use client';

import { useTranslations } from 'next-intl';

export default function LoginForm() {
  const t = useTranslations('auth');
  const tCommon = useTranslations('common');

  return (
    <form>
      <h2>{t('login')}</h2>
      <input placeholder={t('emailPlaceholder')} />
      <button>{tCommon('submit')}</button>
    </form>
  );
}

동적 값 포함 (변수 치환)

'use client';

import { useTranslations } from 'next-intl';

export default function ValidationMessage() {
  const t = useTranslations('validation');

  return (
    <p>{t('minLength', { min: 8 })}</p>
    // 출력: "최소 8자 이상 입력하세요"
  );
}

2. 서버 컴포넌트에서 사용

import { useTranslations } from 'next-intl';

export default function ServerComponent() {
  const t = useTranslations('common');

  return (
    <div>
      <h1>{t('welcome')}</h1>
    </div>
  );
}

참고: Next.js 16에서는 서버 컴포넌트에서도 useTranslations 사용 가능


3. 현재 로케일 가져오기

'use client';

import { useLocale } from 'next-intl';

export default function LocaleDisplay() {
  const locale = useLocale(); // 'ko' | 'en' | 'ja'

  return <div>Current locale: {locale}</div>;
}

4. 언어 전환 컴포넌트

'use client';

import { useLocale } from 'next-intl';
import { useRouter, usePathname } from 'next/navigation';
import { locales, type Locale } from '@/i18n/config';

export default function LanguageSwitcher() {
  const locale = useLocale();
  const router = useRouter();
  const pathname = usePathname();

  const switchLocale = (newLocale: Locale) => {
    // 현재 경로에서 로케일 제거
    const pathnameWithoutLocale = pathname.replace(`/${locale}`, '');

    // 새 로케일로 이동
    router.push(`/${newLocale}${pathnameWithoutLocale}`);
  };

  return (
    <select
      value={locale}
      onChange={(e) => switchLocale(e.target.value as Locale)}
    >
      {locales.map((loc) => (
        <option key={loc} value={loc}>
          {loc.toUpperCase()}
        </option>
      ))}
    </select>
  );
}

'use client';

import Link from 'next/link';
import { useLocale } from 'next-intl';

export default function Navigation() {
  const locale = useLocale();

  return (
    <nav>
      <Link href={`/${locale}/dashboard`}>Dashboard</Link>
      <Link href={`/${locale}/settings`}>Settings</Link>
    </nav>
  );
}

또는 next-intlLink 사용:

import { Link } from '@/i18n/navigation'; // next-intl/navigation에서 생성

export default function Navigation() {
  return (
    <nav>
      <Link href="/dashboard">Dashboard</Link>
      <Link href="/settings">Settings</Link>
    </nav>
  );
}

🌐 URL 구조

기본 언어 (한국어)

http://localhost:3000/              → 한국어 홈
http://localhost:3000/dashboard     → 한국어 대시보드

참고: localePrefix: 'as-needed' 설정으로 기본 언어는 URL에 표시하지 않음

다른 언어

http://localhost:3000/en            → 영어 홈
http://localhost:3000/en/dashboard  → 영어 대시보드
http://localhost:3000/ja/dashboard  → 일본어 대시보드

🔄 자동 로케일 감지

미들웨어가 다음 순서로 로케일을 감지합니다:

  1. URL 경로: /en/dashboard → 영어
  2. 쿠키: NEXT_LOCALE 쿠키 값
  3. Accept-Language 헤더: 브라우저 언어 설정
  4. 기본 언어: 위 모두 실패 시 한국어(ko)

📚 고급 사용법

1. Rich Text 포맷팅

{
  "welcome": "안녕하세요, <b>{name}</b>님!"
}
import { useTranslations } from 'next-intl';

export default function Greeting({ name }: { name: string }) {
  const t = useTranslations();

  return (
    <p
      dangerouslySetInnerHTML={{
        __html: t('welcome', { name, b: (chunks) => `<b>${chunks}</b>` }),
      }}
    />
  );
}

2. 복수형 처리

{
  "items": "{count, plural, =0 {항목 없음} =1 {1개 항목} other {#개 항목}}"
}
const t = useTranslations();

<p>{t('items', { count: 0 })}</p>  // "항목 없음"
<p>{t('items', { count: 1 })}</p>  // "1개 항목"
<p>{t('items', { count: 5 })}</p>  // "5개 항목"

3. 날짜 및 시간 포맷팅

import { useFormatter } from 'next-intl';

export default function DateDisplay() {
  const format = useFormatter();
  const date = new Date();

  return (
    <div>
      <p>{format.dateTime(date, { dateStyle: 'full' })}</p>
      <p>{format.dateTime(date, { timeStyle: 'short' })}</p>
    </div>
  );
}

출력 예시:

  • 한국어: "2025년 11월 6일 수요일"
  • 영어: "Wednesday, November 6, 2025"
  • 일본어: "2025年11月6日水曜日"

4. 숫자 포맷팅

import { useFormatter } from 'next-intl';

export default function PriceDisplay() {
  const format = useFormatter();
  const price = 1234567.89;

  return (
    <div>
      {/* 통화 */}
      <p>{format.number(price, { style: 'currency', currency: 'KRW' })}</p>
      {/* ₩1,234,568 */}

      {/* 퍼센트 */}
      <p>{format.number(0.85, { style: 'percent' })}</p>
      {/* 85% */}
    </div>
  );
}

🛠️ 새 언어 추가하기

1. 언어 코드 추가

// src/i18n/config.ts
export const locales = ['ko', 'en', 'ja', 'zh'] as const; // 중국어 추가

2. 메시지 파일 생성

# src/messages/zh.json 생성
cp src/messages/en.json src/messages/zh.json
# 내용을 중국어로 번역

3. 언어 정보 추가

// src/i18n/config.ts
export const localeNames: Record<Locale, string> = {
  ko: '한국어',
  en: 'English',
  ja: '日本語',
  zh: '中文', // 추가
};

export const localeFlags: Record<Locale, string> = {
  ko: '🇰🇷',
  en: '🇺🇸',
  ja: '🇯🇵',
  zh: '🇨🇳', // 추가
};

4. 서버 재시작

npm run dev

체크리스트

새 페이지/컴포넌트 생성 시 확인 사항:

  • 클라이언트 컴포넌트는 'use client' 지시문 추가
  • useTranslations 훅 import
  • 하드코딩된 텍스트를 번역 키로 대체
  • 새 번역 키를 모든 언어 파일(ko, en, ja)에 추가
  • Link는 로케일 포함 경로 사용 (/${locale}/path)
  • 날짜/숫자는 useFormatter 훅 사용

🧪 테스트 방법

1. 브라우저에서 수동 테스트

1. http://localhost:3000 접속
2. 언어 전환 버튼 클릭
3. URL이 /en, /ja로 변경되는지 확인
4. 모든 텍스트가 올바르게 번역되는지 확인

2. Accept-Language 헤더 테스트

# 영어
curl -H "Accept-Language: en" http://localhost:3000

# 일본어
curl -H "Accept-Language: ja" http://localhost:3000

3. 로케일별 라우팅 테스트

# 한국어
curl http://localhost:3000/

# 영어
curl http://localhost:3000/en

# 일본어
curl http://localhost:3000/ja

⚠️ 주의사항

1. 서버/클라이언트 컴포넌트 구분

// ❌ 잘못된 예 (클라이언트 전용 훅을 서버 컴포넌트에서 사용)
import { useRouter } from 'next/navigation';

export default function ServerComponent() {
  const router = useRouter(); // 에러!
  return <div>...</div>;
}
// ✅ 올바른 예
'use client';

import { useRouter } from 'next/navigation';

export default function ClientComponent() {
  const router = useRouter();
  return <div>...</div>;
}

2. 메시지 키 누락

모든 언어 파일에 동일한 키가 있어야 합니다.

// ❌ ko.json에는 있지만 en.json에 없는 경우
// ko.json
{ "newFeature": "새 기능" }

// en.json
{} // 누락!

해결: 모든 언어 파일에 키 추가

3. 동적 라우팅

// ❌ 로케일 없이 하드코딩
<Link href="/dashboard">Dashboard</Link>

// ✅ 로케일 포함
<Link href={`/${locale}/dashboard`}>Dashboard</Link>

🔗 참고 자료


📝 변경 이력

날짜 버전 변경 내용
2025-11-06 1.0.0 초기 i18n 설정 구현 (ko, en, ja 지원)

💡

번역 키 네이밍 규칙

패턴: {네임스페이스}.{카테고리}.{키}

예시:
- common.buttons.save
- auth.form.emailPlaceholder
- validation.errors.required
- navigation.menu.dashboard

메시지 파일 관리

# 번역 누락 확인 스크립트 (package.json에 추가)
{
  "scripts": {
    "i18n:check": "node scripts/check-translations.js"
  }
}

성능 최적화

  • Code Splitting: 네임스페이스별로 메시지 파일 분리
  • Dynamic Import: 필요한 언어만 로드
  • Caching: 번역 결과 메모이제이션

문서 작성일: 2025-11-06 작성자: Claude Code 프로젝트: Multi-tenant ERP System


관련 파일

프론트엔드

  • src/i18n/config.ts - i18n 설정 (지원 언어, 기본 언어)
  • src/i18n/request.ts - 서버사이드 메시지 로딩
  • src/messages/ko.json - 한국어 메시지
  • src/messages/en.json - 영어 메시지
  • src/messages/ja.json - 일본어 메시지
  • src/middleware.ts - 로케일 감지 + 봇 차단 미들웨어
  • src/app/[locale]/layout.tsx - 루트 레이아웃 (NextIntlClientProvider)
  • src/components/LanguageSwitcher.tsx - 언어 전환 컴포넌트

설정 파일

  • next.config.ts - Next.js 설정 (next-intl 플러그인)

참조 문서

  • claudedocs/architecture/[REF] architecture-integration-risks.md - 아키텍처 통합 위험 분석