Skip to content

developeratul/nextjs-appdir-intl

Repository files navigation

How to internationalize Next.js app directory

In the ever-expanding digital landscape, reaching a global audience is not just a goal but a necessity. Whether you're building a personal portfolio or a sophisticated web application, making it accessible to users around the world is a game-changer. And that's where the magic of internationalization comes into play!

In this blog, we'll embark on a journey to internationalize your Next.js application with app directory, unlocking the power to speak to users in their preferred languages and creating a more inclusive and user-friendly experience. Don't worry if you're new to the concept – we'll guide you through the process step by step, making it an enjoyable and enlightening adventure.

So, grab your favorite coding beverage ☕, put on your explorer hat 🎩, and let's dive into the exciting world of internationalization with Next.js! 🚀🌐

Terminology

  • Locale: An identifier for a set of language and formatting preferences. This usually includes the preferred language of the user and possibly their geographic region.

    • en-US: English as spoken in the United States
    • de-DE: Deutsch as spoken in Germany

Setup

First, let's create a fresh next.js app. Make sure our versions of Next.js match. At the moment, I am using Next v14. To sync up with the package.json file, make sure you checkout this repository created just for this tutorial.

pnpm dlx create-next-app nextjs-appdir-intl

Make sure you are using app dir because this is what we will be covering today.

Install necessary packages:

pnpm add next-intl

We are all set 🚀

Folder structure

├── locales
│   ├── en-US.json
│   └── de-DE.json
├── next.config.js
├── middleware.ts
├── i18n.ts
└── app
    └── [locale]
        ├── layout.tsx
        └── page.tsx

Localized routing

Let's sprinkle some magic into the user experience! Instead of making users figure out which language to choose, why not check what language their browser likes and take them straight to the right page?

Here's the plan:

  • English about page: /en-US/about
  • German about page: /de-DE/about

Let's edit the i18n.ts file:

export const supportedLocales = ["en-US", "de-DE"];
export const defaultLocale = "en-US";

middleware.ts

import createMiddleware from "next-intl/middleware";
import { defaultLocale, supportedLocales } from "./i18n";

export default createMiddleware({
  // A list of all locales that are supported
  locales: supportedLocales,

  // Used when no locale matches
  defaultLocale,
});

export const config = {
  // Match only internationalized pathnames
  matcher: ["/", "/(de-DE|en-US)/:path*"],
};

app/[locale]/layout.tsx

import { defaultLocale, supportedLocales } from "@/i18n";
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import { notFound } from "next/navigation";
import { ReactNode } from "react";
import "./globals.css";

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

interface Props {
  children: ReactNode;
  params: { locale: string };
}

export default function RootLayout(props: Props) {
  const { children, params } = props;

  if (!supportedLocales.includes(params.locale)) notFound();

  return (
    <html lang={params.locale || defaultLocale}>
      <body className={inter.className}>{children}</body>
    </html>
  );
}

It's all it takes. Now if you run the app and refresh, you should be able to see the localized path on the URL.

Localized Next.js url path

Add translations

Now that we have got localized routing and we can keep track of the current locale, let's go ahead and add the translations that we are gonna need.

locales/en-US.json

{
  "home_page": {
    "top_card": "Get started by editing app/page.tsx",
    "cards": {
      "card-1": {
        "title": "Docs",
        "description": "Find in-depth information about Next.js features and API."
      },
      "card-2": {
        "title": "Learn",
        "description": "Learn about Next.js in an interactive course with quizzes!"
      },
      "card-3": {
        "title": "Templates",
        "description": "Explore starter templates for Next.js."
      },
      "card-4": {
        "title": "Deploy",
        "description": "Instantly deploy your Next.js site to a shareable URL with Vercel."
      }
    }
  },

  "common_words": {
    "by": "By"
  }
}

locales/de-DE.json

{
  "home_page": {
    "top_card": "Beginnen Sie mit der Bearbeitung von app/page.tsx",
    "cards": {
      "card-1": {
        "title": "Dokumente",
        "description": "Hier finden Sie ausführliche Informationen zu den Funktionen und der API von Next.js."
      },
      "card-2": {
        "title": "Learn",
        "description": "Erfahren Sie mehr über Next.js in einem interaktiven Kurs mit Quiz!"
      },
      "card-3": {
        "title": "Vorlagen",
        "description": "Entdecken Sie Starter-Vorlagen für Next.js."
      },
      "card-4": {
        "title": "Einsetzen",
        "description": "Stellen Sie Ihre Next.js-Site sofort mit Vercel unter einer gemeinsam nutzbaren URL bereit."
      }
    }
  },

  "common_words": {
    "by": "Von"
  }
}

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published