dynamic i18n locales in next.config.js #54762
-
Hi! According to https://nextjs.org/docs/app/api-reference/next-config-js/redirects#redirects-with-i18n-support I can use i18n locales when I do redirects. Thats great! However, I build a site where the user can add languages in the CMS so I would need to fetch the list of locales dynamically. How can that be done in the next.config.js file? I've tried this but it does not work. const nextConfig = {
async i18n() {
const {getLocales} = require("./src/data/getLocales/getLocales")
const locales = await getLocales();
return {
locales,
defaultLocale: 'en-gb',
}
},
experimental: {
appDir: true,
},
...
}
module.exports = nextConfig |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
I ended up solving this by creating a NPM script that fetches all languages and generates a JS file with an array of langs. I then read that file in the next config like this const locales = require('./data/locales/locales.js')
const nextConfig = {
i18n: {
locales: locales,
defaultLocale: 'en-gb',
},
async redirects() {
return [
{
source: '/quiz/:locale',
destination: '/:locale/quiz',
permanent: true,
}
]
}
...
} Heres the script I wrote to fetch and create the file in /bin/fetchLocales.js #! /usr/bin/env node
const fs = require('fs')
const fetch = require('node-fetch')
const dotenv = require('dotenv');
const envs = dotenv.config();
const apiKey = envs.parsed.MONGODB_API_KEY
const apiHost = envs.parsed.MONGODB_API_HOST
const db = envs.parsed.MONGODB_DB_NAME
const host = envs.parsed.HOST
const specialLocales = [
"en-pem",
"es-pem",
"fr-pem",
"en-cca",
"es-cca"
]
const getLocales = async () => {
const response = await fetch(`${apiHost}/locales?db=${db}&host=${host}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'api-key': apiKey,
}
})
return await response.json();
}
const fetchLocales = async () => {
const locales = await getLocales()
const allLocales = [...locales, ...specialLocales].sort()
if (!fs.existsSync('./data/locales')) {
fs.mkdirSync('./data/locales', { recursive: true })
}
const output = "module.exports = " + JSON.stringify(allLocales, null, 2) + ";"
fs.writeFileSync('./data/locales/locales.js', output );
}
fetchLocales() and last but not least, in package.json I added prescripts like this
|
Beta Was this translation helpful? Give feedback.
I ended up solving this by creating a NPM script that fetches all languages and generates a JS file with an array of langs. I then read that file in the next config like this
Heres the script I wrote to fetch and create the file in /bin/fetchLocales.js