Markus Müller
Markus Müller

Reputation: 188

Next.js url structure for multi language sites

I'm migrating my app to Next.js. Currently I have a url structure like this:

www.example.com/ <-- English
www.example.com/de <-- German
www.example.com/page <-- English
www.example.com/de/page <-- German

So my english website does not have the language in the url. If someone tries to access the website with "en" in the url he will be forwarded.

How would I achieve this in Next.js? Having always two files (i.e. "[language].js" and "index.js") in the /pages directory seems to be not the right solution.

Upvotes: 3

Views: 11776

Answers (3)

rovaniemi
rovaniemi

Reputation: 97

UPDATE: As nunorbatista said: With NextJS 10 you can do this natively. Your next.config.js would look like this:

module.exports = {
  i18n: {
    locales: ['en', 'de'],
    defaultLocale: 'en',
  },
}

Old answer:

The folder structure is correct, but you don’t need to write duplicate code inside [language] folder. Just import the page from ”main” folder. Multilingual is currenly a bit complex to setup with Next.js. Here is the situation at the moment.

If you want to use library

If you want to do it on your own, you should modify them to match your needs.

Upvotes: 4

nunorbatista
nunorbatista

Reputation: 875

With NextJS 10 you can do this natively. Your next.config.js would look like this:

module.exports = {
  i18n: {
    locales: ['en', 'de'],
    defaultLocale: 'en',
  },
}

The defaultLocale is the language for www.example.com/.

Then you can use a library like next-i18next to store the translations.

Upvotes: 6

Markus M&#252;ller
Markus M&#252;ller

Reputation: 188

As of Next.js 9.4 there is an experimental feature "Custom Routes". This provides a more elegent solution. See the discussion here: https://github.com/zeit/next.js/issues/9081

Example usage:

// next.config.js
module.exports = {
  async rewrites() {
    return [
      // Basic `path-to-regexp` usage
      // Query object shape: { id: string }
      { source: "/user/:id", destination: "/user_profile" },

      // Optional Language
      // Query object shape: { lang?: string }
      { source: "/:lang(en|es)?/about", destination: "/about" },

      // Advanced rewrite
      // Query object shape: { id: string } (in addition to dynamic route param)
      { source: "/u/:id", destination: "/user/:id" }
    ];
  }
};

Upvotes: 6

Related Questions