tips / nextjs

How to implement internationalization (i18n) in Next.js

February 14, 2023

I use i18n (Internationalization) built-in support on Next.js.

Next.js has built-in support for internationalized (i18n) routing since v10.0.0. You can provide a list of locales, the default locale, and domain-specific locales and Next.js will automatically handle the routing. — Internationalized Routing https://nextjs.org/docs/advanced-features/i18n-routing

Add Config

Add i18n config to next.config.js file. Write all locales you want to support to locales . And also write default locale to defaultLocale .

module.exports = {
  i18n: {
    locales: ['en', 'ja'],
    defaultLocale: 'ja',
  },
}

There are two locale handling strategies: Sub-path Routing and Domain Routing. Sub-path Routing is /en /fr , Domain Routing is example.com example.fr .

On this site, I chose Sub-path Routing.

For example in BLOG page ( pages/blog.js ) will be like this.

  • /blog
  • /en/blog

After adding that config, Next.js will try to automatically detect based on user’s environment.

You can also check another settings on Next.js Official Docs ( Internationalized Routing ).

Create Switcher

Creating Switcher let user be able to change the language.

You can get current locale with useRouter . And also you can get locale list you are supporting on your website or application.

import Link from "next/link";
import { useRouter } from "next/router";

export const LocaleSwitcher = () => {
  const { locale, locales, asPath } = useRouter()
  return (
    <div>
      {locales && locales.map(localeName => (
        <Link key={localeName} href={asPath} passHref locale={localeName}>
          <a className={locale === localeName ? "current" : "" }>
            {localeName}
          </a>
        </Link>
      ))}
    </div>
  )
}

Put anywhere on your website or application.

File Directory Structure

I generate post page and static page with markdown file. I added file-name.locale.md for displaying localized page.

src/
└── contents/
    ├── pages/
    |   ├── about.en.md
    |   └── about.md
    |
    └── posts/
        ├── blog/
        |   ├── blog-post.en.md
        |   └── blog-post.md
        |
        └── tips/
            ├── tips-post.en.md
            └── tips-post.md

Create component

On /src/pages/about.tsx ( About page ) in this site,

  • Get the contents with getStaticProps
  • Get the data from markdown file with getPageData()
  • Convert to HTML and display the data with marked

This is a snippet of the code from this site. Get locale in getStaticProps , and pass to getPageData() to get markdown file.

import { GetStaticProps, NextPage } from "next";
import { marked } from "marked";

import { getPageData } from "@utils/post";
import { Page } from "@libs/types";

const About: NextPage<{ post: Page }> = ({ post }) => {
  return (
    <div
      className={post.data.slug}
      dangerouslySetInnerHTML={{ __html: marked(post.content) }}
    />
  )
}

export default About

export const getStaticProps: GetStaticProps = async ({ locale }) => {
  const post = await getPageData("pages", "about", locale)

  return {
    props: {
      post,
    }
  }
}

This is example for getPageData() . In locale === "ja" ? postSlug : postSlug + "." + locale , which the markdown file I will get depends on the current locale: about.md or about.en.md .

import fs from "fs";
import path from "path";
import matter from "gray-matter";

export function getPageData(
  type: string, 
  postIdentifier: string,
  locale: string = "ja",
) {
  // .md を除いたファイル名を取得
  const postSlug = postIdentifier.replace(/\.md$/, "");
  // locale に応じたファイルのパスを取得
  const filePath = path.join(contentsDirectory, type, `${locale === "ja" ? postSlug : postSlug + "." + locale}.md`);
  const readFile = fs.readFileSync(filePath, "utf-8");
  const { data, content } = matter(readFile);

  const postData = {
    slug: postSlug,
    data,
    content
  };

  return postData
}

投稿ページや記事の一覧ページも同様に、基本的には getStaticProps で locale を取得し、 markdown ファイルを取得する function に渡して、 locale に応じたファイルを取得して表示します。

Post List Page

I added locale to markdown file for convenience.

---
title: My Blog Post
locale: en
date: "2022-02-11"
category: "blog"
---

...

Getting locale with getStaticProps , and pass to getPosts() to get markdown file.

export const getStaticProps: GetStaticProps = async ({ locale }) => {
  const tipsPosts = await getTypePosts("tips", locale)

  const sortedPosts = tipsPosts.sort((postA, postB) => postA.data.date > postB.data.date ? -1 : 1)

  return {
    props: {
      posts: sortedPosts,
    },
    revalidate: 30
  }
}

After get all file, return the markdown file which has same locale with current locale using filter() .

export function getPosts(
  type: string,
  locale: string = "ja"
) {
    // get the files from specific directory
  const files = getPostsDirectory(type);

  // get the data contains locale from files
  const allPosts = files.map(file => {
    return getPostMeta(file, type, locale)
  });

  let filteredPosts = [];
  // filter the file which has same locale with current locale
  if (locale === "ja") {
    filteredPosts = allPosts.filter(post => post.data.locale === "ja")
  } else { /** en */
    filteredPosts = allPosts.filter(post => post.data.locale === "en")
  };

  return filteredPosts
}

Post Detail Page

Display post detail page using Next.js Dynamic Routes.

src/
└── pages/
    └── tips/
        └── [slug].tsx

In [slug].tsx

  • Get the path list with getPostPaths()
  • Generate path list with getStaticPaths for rendering
  • Get the data from markdown file with getPostByPath()
  • Get the content with getStaticProps
  • Convert to HTML and display the data with marked

Example: getStaticPaths in [slug].tsx

export const getStaticPaths: GetStaticPaths = async ({ locales }) => {
    // Get the path list
  const postPaths = getPostsPaths("tips")

  let paths: any[] = []
  // Generate pass list with map() for rendering
  postPaths.map((path: string) => {
    locales?.map((locale: string) => {
      paths.push({
        params: { slug: `${path}` },
        locale,
      })
    })
  })

  return {
    paths,
    fallback: "blocking"
  }
}

And paths will be like this

{ params: { slug: 'tips-post1' }, locale: 'ja' },
{ params: { slug: 'tips-post1' }, locale: 'en' }

Example: getPostByPath() to get markdown file

export function getPostByPath(
  path: any,
  type: string,
  locale: string = "ja",
) {
  let postData: Post = initialPost;
  const files = getPostsDirectory(type);

  // get the path
  const filteredFiles = files.filter(file => {
    return file.includes(path)
  })

  filteredFiles.map((file) => {
    const tempData = getPost(file, type, locale)
    // return the data from markdown
    // if markdown has the same locale with current locale
    // if it's not, return false
    if (tempData.data.locale === locale) {
      postData = getPost(file, type, locale)
    } else {
      return false
    }
  })

  return postData
}

Go back to the file [slug].tsx , get locale in getStaticProps and pass to getPostByPath() , get the data from markdown, and then pass the data to the component to display the data.

export const getStaticProps: GetStaticProps = async ({ locale, params }) => {
  const post = await getPostByPath(params!.slug, "tips", locale)

  return {
    props: {
      post: post,
      slug: params!.slug,
    },
    revalidate: 600
  }

If the page is not available in English yet

In this case, add <meta name="robots" content="noindex" /> to head tag.

Example: [slug].tsx

On this site, I added localized: boolean to markdown file for convenience. And also display the message.

import Head from "next/head";

const TipsPost: NextPage<PostProps> = ({ post, slug, tags }) => {
  return(
    <>
      <Head>
        {locale === "en" && !post.data.localized && <meta name="robots" content="noindex" />}
      </Head>
      <article>
        <p>This page is not available in English yet.</p>
      <article>
    </>
  )
}

References

Tags

javascripthow-toweb-developer