Create multi language website with Node.js

Lightweight simple translation module with dynamic json storage. Supports plain vanilla node.js apps and should work with any framework (like expressrestify and probably more) that exposes an app.use() method passing in res and req objects. Uses common __(‘…’) syntax in app and templates.

Install all dependencies :

npm install i18n --save

Test

npm test

Create i18n.js in you project folder root level, and paste the code:

var i18n = require('i18n');

i18n.configure({
    // setup some locales - other locales default to en silently
    locales:['en', 'cy'],

    // where to store json files - defaults to './locales' relative to modules directory
    directory: __dirname + '/locales',

    defaultLocale: 'en',
    register: global
  
});

module.exports = async function(req, res, next) {

    const headres = req.headers;
    i18n.init(req, res);
    i18n.setLocale(headres.accept-language);
            

    return next();
};
Create multi language website with React

we initialize the config setting of i18n for more read . The async function used to load i18n instance overall the project. In this function you can set your custom logic and  change language overall. i18n.setLocale() function accept String, pass language code and it will access that language file json. Default i18n accept the language from header accept-language key or you can pass in params.

Now load the i18n.js file in app.js file

var express = require('express');
var bodyParser = require('body-parser');
i18n = require('./i18n');
app = express();
app.use(i18n);

while your app run first time its automatically create locales folder in you project and create json file inside it. How many JSON files are created, its dependence on i18n configuration setting locales:[‘en’, ‘cy’] , in this example it will create two file [en.json and cy.json]

How to access i18n.__() in modules and controller:

you can access it from req.__() or directly

export.module.userCreate = async(req, res) => {
  __('CUSTOM_MESSAGE') 
  /*your logic*/
}

for any other assistance drop a message. Thanks

Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
Yes0
No5
Harinder Singh

Harinder Singh

My name is Harinder Singh and I specialize in Software industry. I consider myself as a life learner. I love learning new concepts, embracing new ideas and reading and searching for innovation.