언어 전환기 구축하기

사용자가 모든 페이지에서 언어를 전환할 수 있도록 허용

문제

사용자가 /en/products/123와 같은 특정 페이지에 있을 때 동일한 페이지를 다른 언어로 보고 싶어 합니다. 언어 전환기(예: 'Français')를 클릭하면 해당 제품 페이지 대신 홈페이지(/fr/)로 돌아가는 경우가 많아 작업 흐름이 중단되고 다시 탐색해야 합니다.

솔루션

현재 URL 경로명을 읽는 클라이언트 컴포넌트를 생성합니다. 경로의 현재 언어 세그먼트를 교체하여 지원되는 다른 모든 언어에 대한 링크 목록을 생성합니다. 또한 클릭 시 기본 설정 쿠키를 설정하여 향후 방문 시 선택이 기억되도록 합니다.

단계

1. 언어 구성 정의하기

i18n.config.ts 파일에 로케일 목록과 사용할 쿠키 이름이 포함되어 있는지 확인하세요.

// i18n.config.ts

export const locales = ['en', 'es', 'fr'];
export const defaultLocale = 'en';
export const localeCookieName = 'NEXT_LOCALE';

2. 언어 전환기 컴포넌트 생성하기

새 파일을 생성합니다. 예를 들어 app/components/LanguageSwitcher.tsx입니다. usePathname와 같은 훅을 사용하려면 클라이언트 컴포넌트여야 합니다.

// app/components/LanguageSwitcher.tsx
'use client';

import { usePathname } from 'next/navigation';
import Link from 'next/link';
import { locales, localeCookieName } from '@/i18n.config';

export default function LanguageSwitcher() {
  const pathname = usePathname();

  // This function sets the cookie
  const setLocaleCookie = (locale: string) => {
    document.cookie = `${localeCookieName}=${locale}; path=/; max-age=31536000; samesite=lax`;
  };

  // This function strips the current locale from the path
  const getRedirectedPath = (locale: string) => {
    if (!pathname) return '/';
    const segments = pathname.split('/');
    segments[1] = locale; // The locale is always the first segment
    return segments.join('/');
  };

  return (
    <div>
      {locales.map((locale) => (
        <Link
          key={locale}
          href={getRedirectedPath(locale)}
          onClick={() => setLocaleCookie(locale)}
          style={{
            display: 'inline-block',
            padding: '0.5rem',
            textDecoration: 'underline',
          }}
        >
          {locale.toUpperCase()}
        </Link>
      ))}
    </div>
  );
}

3. 레이아웃에 전환기 추가하기

새 컴포넌트를 루트 레이아웃 파일 app/[lang]/layout.tsx에 가져와서 배치합니다. 이렇게 하면 모든 페이지에서 표시됩니다.

// app/[lang]/layout.tsx
import LanguageSwitcher from '@/app/components/LanguageSwitcher';

export async function generateStaticParams() {
  // This tells Next.js to pre-render 'en', 'es', and 'fr'
  return [{ lang: 'en' }, { lang: 'es' }, { lang: 'fr' }];
}

export default function RootLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: { lang: string };
}) {
  return (
    <html lang={params.lang}>
      <body>
        <header>
          {/* Add the switcher to your header or nav */}
          <LanguageSwitcher />
        </header>
        <main>{children}</main>
      </body>
    </html>
  );
}

이제 사용자가 /es/products/123에 있을 때 "EN"을 클릭하면 컴포넌트가 새 경로를 /en/products/123로 계산하고 NEXT_LOCALE 쿠키를 'en'으로 설정합니다.