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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…