'How to setup getStaticPaths of multi-locale dynamic pages in Next.js

Today, in my side-project, I got a problem relate to setup getStaticPaths of multi-locale dynamic pages in Next.js. I researched and find out that there are so many people stuck in this problems.

I have created a dynamic page [slug].js to handle all dynamic datas I got from a database. And my website I was working on is also multi-language website which is using next-translate for handle i18n.

In [slug].js, we have to setup a function getStaticPaths to handle all static url. It will be more easier if the website got 1 language, but with more than 2 languages we have to loop it.



Solution 1:[1]

Here is the code I have been used to handle it, I was working with Notion API and use it as a database for a multi-language website:

export async function getStaticPaths({ locales }) {
  const notion = new Client({ auth: process.env.NOTION_API_OFFICIAL_KEYS });

  const databaseId = process.env.NOTION_PAGE_ID_EMBVN_DATABASE_PAGE;
  const response = await notion.databases.query({
    database_id: databaseId,
  });

  let paths = [];

  response.results.forEach((block) => {
    for (const locale of locales) {
      paths.push({
        params: {
          slug: block.properties.embcode.title[0].plain_text.toString(),
        },
        locale,
      });
    }
  });

  return {
    paths,
    fallback: false,
  };
}

With forEach, we will add every pathName of each locale to paths array to return it in the final result of getStaticPaths.

Solution 2:[2]

If the answer help someone, I have reshaped a little the answer of Huu Phong First i get all my post from sanity API then i map on it to get each element , then i map on each element to get only the slug and add on each slug a locale key

export async function getStaticPaths({ locales }) {
  const query = encodeURIComponent(`{
      "posts": *[_type == "post"]  {
        ...,
        categories[]->
      }}
    `)

  const url = `https://${process.env.NEXT_PUBLIC_PROJECT_API}.api.sanity.io/v1/data/query/production?query=${query}`
  const result = await fetch(url).then((res) => res.json())

  const paths = []
  result.result.posts.map((element) => {
    return locales.map((locale) => {
      return paths.push({
        params: { slug: `${element.slug.current}` },
        locale,
      })
    })
  })

  console.log("***---paths---***", paths)

  return {
    paths,
    fallback: true,
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Huu Phong Nguyen
Solution 2 sylvain s