Any app that’s built to scale is going to eventually need localization. At Lazer, building things that scale is our passion, and so we have familiarized ourselves with the intricacies of various localization libraries.
In this quick tutorial, we’re going to be creating a demo project written in NextJS that implements some popular libraries in order to support a second language on our app. But first, let's be clear about what "localization" really means:
Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes.
Localization is the process of adapting internationalized software for a specific region or language by translating text and adding locale-specific components.
In this case, our localization project involves adding french language support to our existing english NextJS app. To do this, we will be using the popular i18next library in combination with locize -- a valuable UI for translators to work on translations. The finished product is available in a sandbox here.
Let's start by installing all of our dependencies.
First, there are several dependencies we need just to get i18next up and running:
In NextJS, all of our "client" modules get run twice: once by the server, and once by the client. So something like this might accidentally mess up your i18n configuration on the server side:
6. Lastly, we just need to initialize it in our project. For frontend, we simply need to wait for the i18next.initPromise to resolve before we render any content. Something like this works well:
7. For backend, we just need to add it as middleware to our express app:
. . . and that's all for setup :)
and use them like this:
Sometimes part of our sentence is variable. If I were to say "David has 5 apples" and numApples is a variable, then you can wrap it in double braces to pass it in as a parameter.
But we can do better than just storing our translations in a json file. Instead, let's use locize to separate concerns: translators can use the locize admin panel to input their translations and they can be automatically pulled in at runtime.
1. Install two more plugins, as well as dotenv if you don't already have it installed
Next, let's visit the Locize Admin Panel, Sign up and create a new project:
We're going to add french (fr) to our project, and create a namespace called "common".
Et voilà! Whenever your app encounters a key that it doesn't have a translation for, it will automatically populate that field in Locize.