reactjsnext.jslocalemultilingual

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

  • 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.