I'm working on a Next.js project where I want to implement locales for dynamic pages using i18n.
The following is defined in my next.config.js file:
module.exports = {
i18n: {
locales: ["en-US", "da-DK", "se-SE", "no-NO", "nl-NL"],
defaultLocale: "en-US",
},
reactStrictMode: true,
images: {
domains: ["images.ctfassets.net"],
},
};
I have a getStaticPaths function I'm using to get data from our CMS (Contentful) which is working fine when I specify a single locale:
export async function getStaticPaths() {
const categories = await ContentfulCategories.getAll();
const paths = categories.map((category) => {
return {
params: { category: category.slug },
locale: "en-US",
};
});
return {
paths,
fallback: false,
};
}
And here is where I'm getting stuck. I've tried inserting an array of the locales from the next config file, but that doesn't work and gives me the following message even though it is defined in the config file:
Error: Invalid locale returned from getStaticPaths for /integration/category/[category], the locale en-US,da-DK,se-SE,no-NO,nl-NL is not specified in next.config.js
How can I specify multiple locales so for instance when I've set the site to example.com/en-US/ it will generate my dynamic page for that locale or one of the others from the config file?
You are using Sub-path Routing strategy. You need to loop available locales from context in getStaticPaths.
From the docs:
When leveraging getStaticPaths, the configured locales are provided in the context parameter of the function under locales and the configured defaultLocale under defaultLocale.
Basically two loops, first categories & then locales. You can use a flatmap to solve this, pseudocode -
export async function getStaticPaths({ locales }) {
const paths = categories.flatMap(category => {
return locales.map(locale => {
return {
params: { category: category.slug },
locale: locale,
};
});
});
}