Best Practices for Implementing Internationalization (i18n) in Next.js Static Exports
October 26, 2024Discover a step-by-step guide on integrating i18n support with static exports in Next.js using next-international. Learn how to set up language files, modify your project structure, and translate both server and client components seamlessly. Perfect for optimizing multilingual Next.js projects.
Recently, I decided to rewrite one of my side projects using Next.js. I've been learning Next.js and wanted to practice by cleaning up my old code.
However, I encountered a challenge: while there are many i18n libraries available, few support static exports. I found a few libraries that claimed to support this feature, but their documentation was sparse, with only brief instructions. This led to a lengthy research process.
Here are the solutions I found:
next-international
Note: The following code examples are in Typescript and are for Next.js using the App Router.
Installation
First, install next-international.
For npm:
For yarn:
Create server.ts and client.ts
Create the following file structure:
server.ts and client.ts:
Prepare the language files
Create file {language name}.ts under locales folder. Like:
Your current file structure looks like this:
Modify Your Existing Files
Move all your routes into an app/[locale]/ folder:
Note: The [locale] placeholder is a literal string, not a variable reference. You should name the folder exactly as [locale].
If your app contains client components, wrap the lowest level components with I18nProviderClient within a layout:
Note: Add a params property to the layout to capture the [locale] value from the URL. For example, visiting /en/ sets [locale] to en, allowing the layout to access the language parameter via params.
Add setStaticParamsLocale and getStaticParams
Add the following:
- Within the root layout, call the
setStaticParamsLocalefunction, passing it thelocalepage parameter. - Export a
generateStaticParamsfunction from the root layout.
Note: You can also add setStaticParamsLocale and getStaticParams to individual pages. If you prefer not to add them to the root layout, you can include them in the specific pages where needed. However, keep in mind that these functions can only be used in server components.
Now, your layout.tsx should be something like this:
Translate Now
Inside server components:
Inside client components:
Static Exports
Inside your next.config.ts, set output to export:
Then, export it to out folder in your project root: