How to generate dynamic paths for non-default locales in Next.js?

For dynamic routes, you have to explicitly return the locales you want to be pre-generated from the getStaticPaths function. If you don’t, Next.js will only generate pages for the default locale.

From Internationalized Routing documentation:

For pages using getStaticProps with Dynamic Routes, all locale
variants of the page desired to be prerendered need to be returned
from getStaticPaths. Along with the params object returned for
paths, you can also return a locale field specifying which locale
you want to render.

This can be achieved by modifying your getStaticPaths function to generate a path for each slug/locale combination.

export async function getStaticPaths({ locales }) { // Get available locales from `context`
   const response = await axios.get('https://api.myappi.com/blog')
   const posts = response.data

   const paths = posts
       .map((post: Props) => locales.map((locale) => ({
           params: { id: post.Id, title: post.Title },
           locale // Pass locale here
       })))
       .flat() // Flatten array to avoid nested arrays
 
   return { paths, fallback: false }
}

Leave a Comment