Skip to content
Rabat, Morocco
Tutorials

Building Type-Safe Multilingual Apps with Next.js 16 and TypeScript

November 25, 2025
Building Type-Safe Multilingual Apps with Next.js 16 and TypeScript
Building multilingual applications is hard. Building type-safe multilingual applications? That's even harder. But here's the thing: with Next.js 16 and TypeScript, you can create i18n systems that catch translation errors at compile time, not runtime. I've built several multilingual applications, and I've learned the hard way that missing translation keys and typos are a real pain. That's why I want to show you how to build a type-safe i18n system that prevents these errors before they reach production. In this tutorial, we're going to build a complete multilingual application with:
  • Type-safe translation keys (catch errors at compile time!)
  • Intelligent locale detection via middleware
  • Dynamic routing with locale support
  • Server Components for optimal performance
  • A production-ready architecture
Let's get started! Before we dive in, let me explain why this matters. Traditional i18n libraries work like this:
// Traditional approach - no type safety
t("welcome.message"); // What if this key doesn't exist? Runtime error!
With a type-safe system:
// Type-safe approach - compile-time checking
t("welcome.message"); // ✅ TypeScript knows this exists
t("welcome.messag"); // ❌ TypeScript error: key doesn't exist!
This saves you from:
  • Runtime errors from typos
  • Missing translations in production
  • Refactoring nightmares when renaming keys
  • Hours of debugging translation issues
Before we start, make sure you have:
  • Node.js 18+ installed
  • Basic knowledge of Next.js and TypeScript
  • Understanding of React Server Components
  • A code editor with TypeScript support
Got everything? Great! Let's build something awesome. First, let's create a new Next.js project:
npx create-next-app@latest multilingual-app --typescript --tailwind --app
cd multilingual-app
Now install the dependencies we'll need:
npm install zod
We'll use Zod for runtime validation, which pairs perfectly with TypeScript's compile-time checking. Let's start by defining our supported locales. Create
src/i18n/config.ts
:
export const locales = ["en", "fr", "pt"] as const;
export type Locale = (typeof locales)[number];

export const defaultLocale: Locale = "en";

export const localeNames: Record<Locale, string> = {
  en: "English",
  fr: "Français",
  pt: "Português",
};

// Validate locale at runtime
export function isValidLocale(locale: string): locale is Locale {
  return locales.includes(locale as Locale);
}
This gives us:
  • Type-safe locale values
  • Runtime validation function
  • A default locale
  • Display names for each locale
Now for the fun part: building a type-safe translation system. Create
src/i18n/translations/en.ts
:
export const en = {
  common: {
    welcome: "Welcome",
    hello: "Hello",
    goodbye: "Goodbye",
  },
  home: {
    title: "Home Page",
    description: "Welcome to our website",
  },
  about: {
    title: "About Us",
    description: "Learn more about our company",
  },
} as const;
Create similar files for other locales. Then create
src/i18n/translations/fr.ts
:
export const fr = {
  common: {
    welcome: "Bienvenue",
    hello: "Bonjour",
    goodbye: "Au revoir",
  },
  home: {
    title: "Page d'accueil",
    description: "Bienvenue sur notre site web",
  },
  about: {
    title: "À propos de nous",
    description: "En savoir plus sur notre entreprise",
  },
} as const;
And
src/i18n/translations/pt.ts
:
export const pt = {
  common: {
    welcome: "Bem-vindo",
    hello: "Olá",
    goodbye: "Adeus",
  },
  home: {
    title: "Página Inicial",
    description: "Bem-vindo ao nosso site",
  },
  about: {
    title: "Sobre Nós",
    description: "Saiba mais sobre nossa empresa",
  },
} as const;
Now create
src/i18n/index.ts
- this is where the magic happens:
import { en } from "./translations/en";
import { fr } from "./translations/fr";
import { pt } from "./translations/pt";
import { Locale } from "./config";

// Create a type that represents all possible translation keys
type TranslationKeys = typeof en;

// Create translations object
const translations = {
  en,
  fr,
  pt,
} as const;

// Helper type to get nested keys
type NestedKeyOf<ObjectType extends object> = {
  [Key in keyof ObjectType & (string | number)]: ObjectType[Key] extends object
    ? `${Key}` | `${Key}.${NestedKeyOf<ObjectType[Key]>}`
    : `${Key}`;
}[keyof ObjectType & (string | number)];

// Type for translation key paths
export type TranslationKey = NestedKeyOf<TranslationKeys>;

// Helper function to get nested value by path string
function getNestedValue(obj: any, path: string): string {
  return path.split(".").reduce((current, key) => current?.[key], obj) ?? path;
}

// Type-safe translation function
export function t(locale: Locale, key: TranslationKey): string {
  const translation = translations[locale];
  return getNestedValue(translation, key);
}

// Export translations for use in components
export { translations };
This system gives us:
  • ✅ Compile-time type checking for translation keys
  • ✅ Autocomplete in your IDE
  • ✅ Refactoring safety (renaming keys updates everywhere)
  • ✅ Runtime fallback if a key is missing
Next.js middleware is perfect for locale detection. Create
src/middleware.ts
:
import { NextRequest, NextResponse } from "next/server";
import { isValidLocale, defaultLocale, locales } from "./i18n/config";

export function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;

  // Check if pathname already has a locale
  const pathnameHasLocale = locales.some(
    (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
  );

  if (pathnameHasLocale) {
    return NextResponse.next();
  }

  // Get locale from cookie, header, or default
  const localeCookie = request.cookies.get("locale")?.value;
  const acceptLanguage = request.headers.get("accept-language");

  let locale = defaultLocale;

  if (localeCookie && isValidLocale(localeCookie)) {
    locale = localeCookie;
  } else if (acceptLanguage) {
    // Parse Accept-Language header
    const preferredLocale = acceptLanguage
      .split(",")[0]
      .split("-")[0]
      .toLowerCase();

    if (isValidLocale(preferredLocale)) {
      locale = preferredLocale;
    }
  }

  // Redirect to locale-prefixed path
  const newUrl = new URL(`/${locale}${pathname}`, request.url);
  return NextResponse.redirect(newUrl);
}

export const config = {
  matcher: [
    // Match all pathnames except:
    // - api routes
    // - _next (Next.js internals)
    // - static files
    // - favicon
    "/((?!api|_next|.*\\..*|favicon.ico).*)",
  ],
};
This middleware:
  • Detects user's preferred language from cookies or browser headers
  • Redirects to locale-prefixed URLs
  • Excludes API routes and static assets
Create the app structure with locale-based routing. First, create
src/app/[locale]/layout.tsx
:
import { ReactNode } from 'react';
import { isValidLocale, defaultLocale, Locale } from '@/i18n/config';
import { notFound } from 'next/navigation';

export function generateStaticParams() {
  return [
    { locale: 'en' },
    { locale: 'fr' },
    { locale: 'pt' },
  ];
}

export default function LocaleLayout({
  children,
  params,
}: {
  children: ReactNode;
  params: { locale: string };
}) {
  const locale = isValidLocale(params.locale) ? params.locale : defaultLocale;

  if (!isValidLocale(params.locale)) {
    notFound();
  }

  return (
    <html lang={locale}>
      <body>{children}</body>
    </html>
  );
}
Create
src/app/[locale]/page.tsx
:
import { isValidLocale, Locale } from '@/i18n/config';
import { t } from '@/i18n';
import { notFound } from 'next/navigation';

export function generateMetadata({ params }: { params: { locale: string } }) {
  const locale = isValidLocale(params.locale) ? params.locale : defaultLocale;

  if (!isValidLocale(params.locale)) {
    notFound();
  }

  return {
    title: t(locale, 'home.title'),
    description: t(locale, 'home.description'),
  };
}

export default function HomePage({ params }: { params: { locale: string } }) {
  const locale = isValidLocale(params.locale)
    ? (params.locale as Locale)
    : defaultLocale;

  if (!isValidLocale(params.locale)) {
    notFound();
  }

  return (
    <main>
      <h1>{t(locale, 'home.title')}</h1>
      <p>{t(locale, 'home.description')}</p>
      <p>{t(locale, 'common.welcome')}</p>
    </main>
  );
}
Create a client component for switching languages. Create
src/components/LanguageSwitcher.tsx
:
'use client';

import { usePathname, useRouter } from 'next/navigation';
import { locales, localeNames, type Locale } from '@/i18n/config';
import { isValidLocale } from '@/i18n/config';
import { useTransition } from 'react';

export function LanguageSwitcher() {
  const router = useRouter();
  const pathname = usePathname();
  const [isPending, startTransition] = useTransition();

  // Extract current locale from pathname
  const currentLocale = pathname.split('/')[1] as Locale;
  const currentPath = pathname.split('/').slice(2).join('/');

  const handleLocaleChange = (newLocale: Locale) => {
    // Set cookie
    document.cookie = `locale=${newLocale}; path=/; max-age=31536000`; // 1 year

    // Navigate to new locale
    startTransition(() => {
      router.push(`/${newLocale}/${currentPath}`);
    });
  };

  return (
    <div className="language-switcher">
      {locales.map((locale) => (
        <button
          key={locale}
          onClick={() => handleLocaleChange(locale)}
          disabled={isPending || locale === currentLocale}
          className={locale === currentLocale ? 'active' : ''}
        >
          {localeNames[locale]}
        </button>
      ))}
    </div>
  );
}
Create an about page:
src/app/[locale]/about/page.tsx
:
import { isValidLocale, Locale, defaultLocale } from '@/i18n/config';
import { t } from '@/i18n';
import { notFound } from 'next/navigation';

export function generateMetadata({ params }: { params: { locale: string } }) {
  const locale = isValidLocale(params.locale) ? params.locale : defaultLocale;

  if (!isValidLocale(params.locale)) {
    notFound();
  }

  return {
    title: t(locale, 'about.title'),
    description: t(locale, 'about.description'),
  };
}

export default function AboutPage({ params }: { params: { locale: string } }) {
  const locale = isValidLocale(params.locale)
    ? (params.locale as Locale)
    : defaultLocale;

  if (!isValidLocale(params.locale)) {
    notFound();
  }

  return (
    <main>
      <h1>{t(locale, 'about.title')}</h1>
      <p>{t(locale, 'about.description')}</p>
    </main>
  );
}
Now let's see the type safety in action. Try this:
// ✅ This works - TypeScript knows the key exists
t("en", "common.welcome");

// ❌ This gives a TypeScript error - key doesn't exist!
t("en", "common.welcom"); // Error: Argument of type '"common.welcom"' is not assignable

// ❌ This also gives an error - invalid locale
t("es", "common.welcome"); // Error: Argument of type '"es"' is not assignable
Your IDE will autocomplete available keys, and TypeScript will catch errors before you even run the code! Sometimes you need dynamic values in translations. Let's extend our system: Update
src/i18n/translations/en.ts
:
export const en = {
  common: {
    welcome: "Welcome",
    hello: "Hello",
    goodbye: "Goodbye",
    greeting: (name: string) => `Hello, ${name}!`,
  },
  // ... rest of translations
} as const;
Update the translation function to handle functions:
export function t(
  locale: Locale,
  key: TranslationKey,
  params?: Record<string, string | number>
): string {
  const translation = translations[locale];
  const value = getNestedValue(translation, key);

  if (typeof value === "function") {
    // For function-based translations, you'd need to handle this differently
    // This is a simplified example
    return value(params?.name as string);
  }

  // Simple parameter replacement
  if (params && typeof value === "string") {
    return Object.entries(params).reduce(
      (str, [key, val]) => str.replace(`{${key}}`, String(val)),
      value
    );
  }

  return value;
}
Create a test to verify type safety:
// src/__tests__/i18n.test.ts
import { t } from "@/i18n";
import { Locale } from "@/i18n/config";

describe("i18n", () => {
  it("should translate valid keys", () => {
    expect(t("en" as Locale, "common.welcome")).toBe("Welcome");
    expect(t("fr" as Locale, "common.welcome")).toBe("Bienvenue");
  });

  it("should handle missing keys gracefully", () => {
    // TypeScript should prevent this, but runtime fallback is good too
    const result = t("en" as Locale, "common.welcome" as any);
    expect(result).toBeDefined();
  });
});
Here are some tips I've learned from building multilingual apps: Use a clear hierarchy:
common.* - Shared across pages
home.* - Homepage specific
about.* - About page specific
Create a script to ensure all locales have the same keys:
// scripts/validate-translations.ts
import { en } from "../src/i18n/translations/en";
import { fr } from "../src/i18n/translations/fr";
import { pt } from "../src/i18n/translations/pt";

function getAllKeys(obj: any, prefix = ""): string[] {
  return Object.keys(obj).flatMap((key) => {
    const fullKey = prefix ? `${prefix}.${key}` : key;
    if (typeof obj[key] === "object" && obj[key] !== null) {
      return getAllKeys(obj[key], fullKey);
    }
    return [fullKey];
  });
}

const enKeys = getAllKeys(en);
const frKeys = getAllKeys(fr);
const ptKeys = getAllKeys(pt);

const missingInFr = enKeys.filter((k) => !frKeys.includes(k));
const missingInPt = enKeys.filter((k) => !ptKeys.includes(k));

if (missingInFr.length > 0 || missingInPt.length > 0) {
  console.error("Missing translations:", { missingInFr, missingInPt });
  process.exit(1);
}
Server Components are perfect for i18n because:
  • Translations are resolved on the server
  • No client-side JavaScript for static content
  • Better performance
For languages with complex pluralization rules, consider using a library like
i18next
or implement your own pluralization logic.
Solution: Use TypeScript's type system. If you add a key to one locale, TypeScript will remind you to add it to others. Solution: TypeScript catches this at compile time. Your IDE will autocomplete available keys. Solution: Test your middleware with different browser settings. The cookie fallback ensures persistence. When deploying:
  1. Generate Static Params: Use
    generateStaticParams()
    to pre-render all locale variants
  2. Set Default Locale: Ensure your default locale is always available
  3. Handle 404s: Redirect invalid locales to default locale
  4. SEO: Use
    hreflang
    tags for better SEO
Building type-safe multilingual applications with Next.js 16 and TypeScript gives you:
  • ✅ Compile-time error detection
  • ✅ Better developer experience with autocomplete
  • ✅ Refactoring safety
  • ✅ Production-ready architecture
  • ✅ Optimal performance with Server Components
The combination of Next.js 16's Server Components and a type-safe i18n system creates a powerful foundation for building multilingual applications that are both developer-friendly and performant. Start with this foundation and extend it based on your needs. Add more locales, implement pluralization, or integrate with translation management systems. The type safety will guide you every step of the way.
  1. Extend the System: Add more locales or translation features
  2. Integrate with CMS: Connect translations to a content management system
  3. Add Pluralization: Implement proper pluralization rules
  4. Optimize Performance: Cache translations and optimize bundle sizes
Happy building! 🚀

Enjoyed this tutorial?

Seriously, thank you for spending your time here. If you made it to the end, you’re the kind of person who cares about craft, not just quick fixes.If you’d like to support my work, pick one (no pressure). It genuinely helps me keep writing and improving these tutorials.
Subscribe to get a heads-up when I publish the next one. I keep it low-volume, and I only send what I’d personally want to read.

Subscribe to Josias's Newsletter

I occasionally write about software engineering, technology, and share thoughts on innovation and engineering.
One last thing: if you know someone who’d benefit from this, sharing it with them is one of the best compliments you can give. I appreciate you.