[SOLVED] How to add translated routes (translating the route paths) in a NextJS app?

Issue

This Content is from Stack Overflow. Question asked by cbdeveloper

I’m creating a NextJS web-app that will be deployed in multiple countries. But it’ll be deployed separately. I’ll change only the env.country variables on each deploy.

The issue is that I have some routes with meaningful slugs that need to be translated for the language of the country.

Ex:

de: '/route-path-in-de',
es: '/route-path-in-es',
fr: '/route-path-in-fr',

Since NextJS uses a file/folder based routing system. What is the best way for me to achieve this? Will I need to create a file per translation, like?

pages/
  route-path-in-de.tsx
  route-path-in-es.tsx
  route-path-in-fr.tsx

Is that the only way?



Solution

This is how I solved it.

  • Added a pages/[slug].tsx file
  • Use getStaticPaths and getStaticProps to render the translated slugs,

[slug].tsx

export const getStaticPaths: GetStaticPaths = async () => {
  const slugs = ['route-path-in-de', 'route-path-in-es', 'route-path-in-fr'];
  return {
    paths: slugs.map((item) => ({ params: { slug: item } })),
    fallback: 'blocking',
  };
};


export const getStaticProps: GetStaticProps<PageProps, { slug: string }> = async (context) => {
  const slug = context.params?.slug as string;
  // Do data fetching
  return {
    props: {
      // Data
    },
  };
};

type PageProps = {}

const Page: NextPage<PageProps> = (props) => {
  // Get the props
  // return whatever the page should return
};

export default Page;


This Question was asked in StackOverflow by cbdeveloper and Answered by cbdeveloper It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?