BK52
BK52

Reputation: 934

NextJS - Routing with different language

I try to create multilanguage website with Next JS.

I'm using next-translate package for translation.

For the posts I use static generation.

|-> pages
  |-> post
    |-> [slug].js
|-> i18n.json
|-> next.config.js

Problem

When I use default language ('tr') I successfully navigate http://localhost:3000/post/title-tr

But If I changed to language to 'en', library add 'en' to path then try to navigate http://localhost:3000/en/post/title-en and returns 404 page.

Solution I tried

In next.config.js I add rewrites method. But It didn't work.

require('dotenv').config();
const nextTranslate = require('next-translate');

module.exports = nextTranslate({
    async rewrites() {
        return [
            {
                source: '/en/post/:path*',
                destination: '/post',
            },
        ]
    },

    env: {
        NEXT_PUBLIC_URL: process.env.NEXT_PUBLIC_URL,
    },
})

Where should I solve this problem? Routing, config files or Link component?

i18n.json

{
    "locales": ["tr", "en"],
    "defaultLocale": "tr",
    "pages": {
      "*": ["common","country","position"]
    }
}

Link component I used

<Link key={`L${item.id}`} href="/post/[slug]" as={`/post/${slug(item.title)}-${item.id}`}></Link>

[slug].js

function Post({ data }){
  return <>...</>
}

export async function getStaticPaths() {
   const { data } = await fetch('fromAPI');
   return {
        paths: data.map(item => {
            return {
                params:
                {
                    slug: `${slug(item.title)}-${item.id}`
                }
            }
        }),
        fallback: false
    }
}

export async function getStaticProps({ params }) {
    const { data } = await fetch('fromAPI');
    return { props: { data} }
}

export default Post;

Upvotes: 0

Views: 3116

Answers (1)

hackarmannen
hackarmannen

Reputation: 506

You have to add a path for every locale as shown in the documentation: https://nextjs.org/docs/advanced-features/i18n-routing#dynamic-routes-and-getstaticprops-pages

// [slug].js
export const getStaticPaths = ({ locales }) => {
  return {
    paths: [
      { params: { slug: 'post-1' }, locale: 'tr' },
      { params: { slug: 'post-1' }, locale: 'en' },
    ],
    fallback: true,
  }
}

When I use default language ('tr') I successfully navigate http://localhost:3000/post/title-tr But If I changed to language to 'en', library add 'en' to path then try to navigate http://localhost:3000/en/post/title-en and returns 404 page.

If no locale is provided only the defaultLocale will be generated. If fallback is false, then any paths not returned by getStaticPaths will result in a 404 page. So right now you're only generating the defaultLocale "tr" and all other paths with different locales will result in a 404 page.

Upvotes: 2

Related Questions