Internationalization (i18n) has always been complex especially when requirements involve translating user generated contents. I will try to explain a simple way of creating, using and storing translations of texts from a database.
The standard way internalization works is to store translations for each language and retrieve them with a key. The translated messages are usually stored in a translation.json file and a translation service will take care of using the key to search the file and replace the key with the found value or a default value if any.
I used Azure Cosmos DB SQL API as my database, NodeJS on the backend, ReactJS on the frontend and mkdirp npm package to create directories and write translated languages on the server. These methods will work with any backend like Azure Functions, AWS Lamda.
Set up Azure Cosmos DB
Follow this tutorial to create a free Cosmos DB on Azure. Store unstructured data using Azure Functions and Azure Cosmos DB
Write some JSX code
Import import ‘./i18n’ and wrap your App Component with Suspense. Your index.js should look like this:
Set up Database
Next is to add a configuration file to for database settings and seed data. Add config.js file and content should look like this:
This will create a JSON file for each language listed as a doc in the database. You can modify the content of the generated JSON files locally or directly from Azure data explorer. You can also create a basic CRUD admin interface on your application and manage them from there.
Now you can use and inject translated text into your HTML code by using the translation Key. This is a simple approach and sometimes acceptable.
Finally, include script in the npm build scripts in the package.json file
Executing npm run translate will extract translations from Azure Cosmos DB and generate JSON files on the server.
This is by no means a perfect solution. It is more like a working solution that can be modified and engineered better for your requirements. You can also move the translation database to be consumed through an azure function, cached or as part of a micro-services architecture.
Hope this article was helpful and enjoy!