'How to setup i18n translated URL routes in Next.js?
I am using Next.js i18n-routing to setup multi-language website. This works perfectly. If I create a file in /pages/about.js this will create URLs based on my locale settings, for example:
- EN ->
/about - DE ->
/de/about - ES ->
/es/about
That is all fine.
What if I want to have a translated URL routes for each language? I am stuck on how to set this up...
- EN ->
/about - DE ->
/de/uber-uns - ES ->
/es/nosotros
?
Solution 1:[1]
You can achieve translated URL routes by leveraging rewrites in your next.config.js file.
module.exports = {
i18n: {
locales: ['en', 'de', 'es'],
defaultLocale: 'en'
},
async rewrites() {
return [
{
source: '/de/uber-uns',
destination: '/de/about',
locale: false // Use `locale: false` so that the prefix matches the desired locale correctly
},
{
source: '/es/nosotros',
destination: '/es/about',
locale: false
}
]
}
}
Furthermore, if you want a consistent routing behaviour during client-side navigations, you can create a wrapper around the next/link component to ensure the translated URLs are displayed.
import { useRouter } from 'next/router'
import Link from 'next/link'
const pathTranslations = {
de: {
'/about': '/uber-uns'
},
es: {
'/about': '/sobrenos'
}
}
const TranslatedLink = ({ href, children }) => {
const { locale } = useRouter()
// Get translated route for non-default locales
const translatedPath = pathTranslations[locale]?.[href]
// Set `as` prop to change displayed URL in browser
const as = translatedPath ? `/${locale}${translatedPath}` : undefined
return (
<Link href={href} as={as}>
{children}
</Link>
)
}
export default TranslatedLink
Then use TranslatedLink instead of next/link in your code.
<TranslatedLink href='/about'>
<a>Go to About page</a>
</TranslatedLink>
Note that you could reuse the pathTranslations object to dynamically generate the rewrites array in the next.config.js and have a single source of truth for the translated URLs.
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 |
