ExpressJS - Internationalization



Internationalization or I18N refers to the ability of an Application to serve users in multiple and different languages. We can implement internationalization in express js easily using following modules−

  • i18next− core framework for Internationalization.

  • i18next-express-middleware− middleware to detect user language and provide i18n functionality to express routes and requests.

  • i18next-node-fs-backend− backend to load messages from file system.

Installing i18n modules

We can use the following command to install above i18n modules using npm.

npm install --save i18next  i18next-http-middleware i18next-fs-backend

Creating Translation files

Let's us create two translation files, one for default local english and one for french. We'll store a sample message as Hello! in both languages.

Folder Structure

locales
 en
    translation.json 
 fr
     translation.json 

en - translation.json

{
   "welcome": "Welcome to tutorialspoint!",
   "greeting": "Hello {{name}}!"
}

fr - translation.json

{
   "welcome": "Bienvenue sur tutorielspoint!",
   "greeting": "Bonjour {{name}}!"
}

Initialize i18n and use

const i18next = require('i18next');
const Backend = require('i18next-fs-backend');
const middleware = require('i18next-http-middleware');

i18next
  .use(Backend)
  .use(middleware.LanguageDetector)
  .init({
    fallbackLng: 'en', // Default language
    backend: {
      loadPath: './locales/{{lng}}/translation.json'
    },
    detection: {
      // Order and types of detection
      order: ['querystring', 'cookie', 'header'],
      lookupQuerystring: 'lng',
      lookupCookie: 'i18next',
      caches: ['cookie']
    },
    interpolation: {
      escapeValue: false // React already handles escaping
    }
  });

app.use(middleware.handle(i18next));

Explanation

  • use(Backend)− use i18next-fs-backend as backend to read translatio files from file system.

  • use(middleware.LanguageDetector)− allows application to decide language based on Accept-Language header sent by consumer.

  • fallbackLng− default language as english if no translation found for a key.

  • loadPath− load translation files from relevant language folder identified by {{lng}} attribute.

  • app.use(i18nextMiddleware.handle(i18next))− directs express to use i18next middleware.

t function

i18next-express-middleware provides express request a translation function t. t function looks for the key in the messages loaded by i18n and returns the corresponding language translation.

Define express routes and use t function

app.get('/', (req, res) => {
  res.status(200);
  res.send(req.t('welcome')); // Uses the appropriate translation
});

app.get('/greet/:name', (req, res) => {
  res.status(200);
  res.send(req.t('greeting', { name: req.params.name }));
});

app.listen(3000);

Example Usage

  • English− http://localhost:3000/

  • French− http://localhost:3000/?lng=fr

Complete Example - Internationalization

Following is the complete code of index.js

index.js

var express = require('express');
const i18next = require('i18next');
const Backend = require('i18next-fs-backend');
const middleware = require('i18next-http-middleware');

var app = express();

i18next
  .use(Backend)
  .use(middleware.LanguageDetector)
  .init({
    fallbackLng: 'en', // Default language
    backend: {
      loadPath: './locales/{{lng}}/translation.json'
    },
    detection: {
      // Order and types of detection
      order: ['querystring', 'cookie', 'header'],
      lookupQuerystring: 'lng',
      lookupCookie: 'i18next',
      caches: ['cookie']
    },
    interpolation: {
      escapeValue: false // React already handles escaping
    }
  });

app.use(middleware.handle(i18next));

app.get('/', (req, res) => {
  res.status(200);
  res.send(req.t('welcome')); // Uses the appropriate translation
});

app.get('/greet/:name', (req, res) => {
  res.status(200);
  res.send(req.t('greeting', { name: req.params.name }));
});

app.listen(3000);

Output

In browser, open http://localhost:3000/ to use english based translation file.

English Locale

http://localhost:3000/greet/mahesh

English Locale

In browser, open http://localhost:3000/?lng=fr to use french based translation file.

French Locale

http://localhost:3000/greet/mahesh?lng=fr

French Locale
Advertisements