samuelg0rd0n
samuelg0rd0n

Reputation: 1258

How do I localize routes with next.js and next-i18next?

I need to change the name of the route when I change the language. For example, I have a route /en/career but when I change to Czech language, I need a route /cs/kariera. Basically I need the URLs to be localized. Right now, when I'm on /en/career and change language to cs, I get /cs/career. This page should not exist at all and when I render the page on server, I correctly get 404. Can I do something like this with next-i18next package? If so, how?

I found this package https://github.com/vonschau/next-routes-with-locale which probably does exactly what I need but it's apparently no longer maintained and doesn't work under next.js 8.

Upvotes: 9

Views: 7970

Answers (3)

Branislav
Branislav

Reputation: 130

Solution for nextjs 13 and app router is to use next rewrites with next-intl.

Resources:

(in: next.config.js):

 rewrites() {
    return [
      {
        source: '/cs/kariera',
        destination: '/en/career',
      },
    ]
  },

File structure: /app/[lang]/career/page.tsx

You want to map url to directory:

  • /cs/kariera -> /cs/career
  • /en/career -> /en/career

Myo riginal answer: Details: Translating URLs in Next.js 13 with App directory and next-intl

Upvotes: 1

samuelg0rd0n
samuelg0rd0n

Reputation: 1258

What I did eventually was to use next-routes package and defined specific route for every page, such as:

module.exports = routes()
    .add('en-career-listing', '/en/career/:listing', 'career/listing')
    .add('cs-career-listing', '/cs/kariera/:listing', 'career/listing')
    .add('en-career', '/en/career', 'career')
    .add('cs-career', '/cs/kariera', 'career')
    .add('en-our-story', '/en/our-story', 'our-story')
    .add('cs-our-story', '/cs/nas-pribeh', 'our-story')

And I also had to create a custom Link component based on next/link where I manually added the language to URL.

Upvotes: 7

felixmosh
felixmosh

Reputation: 35583

next-i18next supports this functionality, it called locale subpaths.

You need to configure: new NextI18Next({ localeSubpaths: 'foreign' }), and then use the Link & Router that NextI18Next instance has on it, not the next/router.

Upvotes: 0

Related Questions