Files
sam-react-prod/claudedocs/guides/[IMPL-2025-11-06] i18n-usage-guide.md
유병철 f0987127eb feat(WEB): QMS 검사 모달 개선, 전자결재/생산대시보드/템플릿 기능 수정
- QMS: InspectionModal/InspectionModalV2 개선, mockData 정리
- 전자결재: DocumentCreate 기능 수정
- 생산대시보드: ProductionDashboard 개선
- 템플릿: IntegratedDetailTemplate/UniversalListPage 기능 수정
- 문서: i18n 가이드 업데이트, 문서뷰어 아키텍처 계획 추가

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-03 09:09:05 +09:00

21 KiB

next-intl 다국어 설정 가이드

개요

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


적용 현황 분석 (2026-02-03 기준)

인프라 상태: 완비

항목 상태 설명
라이브러리 next-intl ^4.4.0 설치 및 설정 완료
지원 언어 ko, en, ja 3개 locale
번역 파일 src/messages/{ko,en,ja}.json 13개 네임스페이스, ~215개 키
미들웨어 src/middleware.ts locale 라우팅 + 인증 통합 완료
Provider [locale]/layout.tsx NextIntlClientProvider 정상
URL 라우팅 localePrefix: 'as-needed' ko는 URL 생략, en/ja는 prefix

실제 적용 현황: 극히 일부만 적용

useTranslations 사용 중인 파일: 3개 (전체의 ~1% 미만)

파일 사용 네임스페이스
src/components/auth/LoginPage.tsx auth, common, validation
src/components/auth/SignupPage.tsx auth, signup, validation
src/app/[locale]/layout.tsx Provider 설정만

하드코딩된 한국어가 있는 파일: ~1,131개

영역별 하드코딩 현황

영역 파일 수 주요 내용
business/ (건설) ~171 계약, 입찰, 견적, 기성, 현장관리, 노무, 단가
items/ (품목) ~101 품목마스터, BOM, 폼, 동적 품목관리
accounting/ (회계) ~69 거래처, 입출금, 매출, 매입, 어음, 카드
settings/ (설정) ~59 계정, 권한, 팝업, 구독, 회사정보, 직급, 휴가정책
hr/ (인사) ~45 직원, 근태, 휴가, 급여, 카드, 부서
production/ (생산) ~38 작업지시, 작업일지, 검사, 작업자화면
ui/ (공통 UI) ~26 file-list, confirm-dialog, error-card, inputs 등
approval/ (결재) ~26 결재 워크플로우, 문서생성, 상세
quotes/ (견적) ~21 견적 등록, 관리, 문서, 계산
outbound/ (출고) ~21 출고증, 배차차량
quality/ (품질) ~13 제품검사, 수입검사
기타 (dashboard, board 등) ~541 대시보드, 게시판, CRM 등

하드코딩 유형 분류

1. Config 파일 (~47개) - 페이지 타이틀, 설명, 라벨

// 예: vehicleDispatchConfig.ts
title: '배차차량 상세',
description: '배차차량 정보를 조회합니다',
backLabel: '목록',

2. JSX 직접 텍스트 - 버튼, 라벨, placeholder

<Button>삭제</Button>
placeholder="거래처명"
<Label>비고</Label>

3. 토스트/알림 메시지

toast.success('저장되었습니다');
toast.error('삭제에 실패했습니다');

4. 상태/상수 정의 (types.ts)

export const STATUS_LABELS = { draft: '작성대기', completed: '작성완료' };
export const FREIGHT_COST_LABELS = { prepaid: '선불', collect: '착불' };

5. 로딩/에러 상태

if (isLoading) return <div>로딩 ...</div>;  // 79+ 인스턴스

6. Mock 데이터 (~7개)

siteName: '위브 청라',
orderCustomer: '두산건설(주)',

번역 파일 동기화 상태

비교 상태 이슈
ko ↔ en 동기화 완료 231줄 일치
ko ↔ ja 1건 누락 auth.loggingIn 키 없음 (ja.json)

현재 번역 파일 네임스페이스

common       : ~25개 키 (기본 UI 액션)
auth         : ~63개 키 (로그인, 회원가입, 역할, 직급)
signup       : ~14개 키 (업종, 회사규모)
navigation   : ~10개 키 (메인 메뉴)
dashboard    : ~10개 키 (대시보드 위젯)
inventory    : ~15개 키 (재고관리)
finance      : ~11개 키 (회계)
hr           : ~14개 키 (인사)
crm          : ~8개 키 (고객관리)
settings     : ~13개 키 (설정)
errors       : ~7개 키 (에러 메시지)
validation   : ~6개 키 (폼 유효성)
messages     : ~8개 키 (성공/실패 알림)

작업 규모 (전체 적용 시)

작업 항목 수량 비고
번역 키 추출 대상 파일 ~1,131개 반복적 패턴 작업
추가 필요 번역 키 (추정) 3,0005,000개 3개 언어 동기화 필요
Config 파일 전환 ~47개 패턴 동일, 일괄 처리 가능
공통 UI 컴포넌트 ~26개 영향 범위 넓음 (전체 앱)
비즈니스 컴포넌트 ~1,000+개 단순 반복이나 양 많음

단계별 적용 계획 (권장)

Phase 1: 공통 기반 - 효과 가장 큼

  • 공통 UI 컴포넌트 26개 (confirm-dialog, error-card, inputs 등)
  • 공통 라벨 (저장, 삭제, 취소, 검색, 로딩 중... 등)
  • "로딩 중..." 같은 반복 문자열 일괄 처리
  • 이것만 해도 전체 앱에 영향

Phase 2: Config 파일 - 기계적 작업

  • 47개 config 파일의 title/description/label
  • 패턴이 동일해서 일괄 처리 가능

Phase 3: 영역별 비즈니스 컴포넌트

  • accounting (69개) → hr (45개) → production (38개) → ...
  • 영역당 번역 네임스페이스 1개씩 추가
  • business/ (171개)가 가장 큰 덩어리

Phase 4: 나머지 + 검증

  • 누락 확인, 빌드 테스트
  • 실제 언어 전환 테스트 (ko → en → ja)
  • ja.json auth.loggingIn 누락 수정

즉시 수정 필요 사항

  1. ja.json 누락 키: auth.loggingIn 추가 필요
    • ko: "loggingIn": "로그인 중..."
    • en: "loggingIn": "Logging in..."
    • ja: (누락) → "loggingIn": "ログイン中..." 추가

📦 설치된 패키지

{
  "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 지원)
2026-02-03 1.1.0 전체 프로젝트 다국어 적용 현황 분석 추가 (하드코딩 현황, 단계별 적용 계획)

💡

번역 키 네이밍 규칙

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

예시:
- 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 - 아키텍처 통합 위험 분석