Search code examples
next.jsnext-i18nextnextjs-dynamic-routing

nextjs dynamic routes doesn't work with next-i18next


I just added next-i18next in my nextjs project following the official guide and everything seemed to be in order, but when I change the language from default (Italian) to English and I go to the detail of an entity then I get 404. This happens only with the dynamic routes and only with the language that is not the default one.

I am going to show you more details.

My next-i18next.config.js file:

module.exports = {
  i18n: {
    defaultLocale: "it",
    locales: ["it", "en"],
  },
};

[id].tsx

//My NextPage component...

export async function getStaticPaths() {
  const paths = await projects.find()?.map((_project) => ({
    params: { id: _project.id + "" },
  }));

  return {
    paths,
    fallback: false,
  };
}

export async function getStaticProps({
  locale,
  ...rest
}: {
  locale: string;
  params: { id: string };
}) {
  const project = await projects.findOne({id: rest.params.id})

  const seo: Seo = {
    //...
  };
  
  //This row is not the problem, since it persists even if I remove it. Also I am sure that the project exists.
  if (!project?.id) return { notFound: true };

  return {
    props: {
      ...(await serverSideTranslations(locale, [
        "common",
        "footer",
        "projects",
      ])),
      seo,
      project,
    },
  };
}

index.tsx (under projects folder)

const Projects: NextPage<Props> = ({ /*...*/ }) => {
  //...
  const router = useRouter();
  
  return <button onClick={() =>
          router.push({
            pathname: `/projects/[slug]`,
            query: { slug: project.slug },
          })
        }>Read more</button>
}

Also I get the error Error: The provided 'href' (/projects/[slug]) value is missing query values (slug) to be interpolated properly. when I try to change the language while I am in the detail of the project with the italian language set, but I think I did it right according to this doc. As I said before, instead, if I try to go into the dynamic route after having changed the language to "en" then I go to 404 page.

Do you have any suggestions to solve this problem?


Solution

  • I solved this by updating the mothod getStaticPaths to:

    export async function getStaticPaths({ locales }: { locales: string[] }) {
      const projects = getProjects({ locale: "it" });
      const paths = projects.flatMap((_project) => {
        return locales.map((locale) => {
          return {
            params: {
              type: _project.slug,
              slug: _project.slug,
            },
            locale: locale,
          };
        });
      });
    
      return {
        paths,
        fallback: true,
      };
    }
    

    So there must be passed the locale into the paths.