Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

reactjs - 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 -> /it/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 -> /it/nosotros

?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...