Özgür GÜL

Localization In Express Js

Localization in Node.js servers that written with Express.js is not a big deal. You don’t even need to use a library for localization in some cases. I’ll show you an example.

Let’s say you have your language strings in a json at global scope (can be in a file or db too, depends on your lazyness) :

var languageData = {
    'en': {
        'LOGIN_BTN': 'Login now',
        'REGISTER_BTN': 'Register'
    },
    'tr': {
        'LOGIN_BTN': 'Giris',
        'REGISTER_BTN': 'Kayit'
    }
}

Let’s create a simple middleware which will do the all business:

function getLanguageStrings(req, res, next) {
    var lang = req.acceptsLanguages('en', 'tr', 'fr')
    var selectedLang = lang ? lang : 'en' // default to english
    req.languageStrings = languageData[selectedLang]
    next()
}

Above, I used acceptsLanguages() method to get the preferred language of browser, but you can set a cookie from client side and read it in our middleware if you want to.

With the req.languageStrings = languageData[selectedLang] line, I’ve attached our language strings to current request, so that next middleware can use it.

Let’s use our middleware:

app.use(getLanguageStrings)

With above usage, our middleware will work with every request, but you might want to restrict it to some routes:

app.get("/about", getLanguageStrings, function(req, res) {
    // rendering...
})

Using with View Engines (Nunjuck, EJS etc…)

To render our strings to HTML, we need to pass them to rendering engine:

app.get("/about", function (req, res) {
    res.render("info.html", { 
        languageStrings: req.languageStrings
    })
})

In view, you now use it with your preferred template engine (nunjucks):

<!-- nunjucks usage -->
<button class="btn"></button>
<button class="btn"></button>

<!-- ejs usage -->
<button class="btn"><% languageStrings.LOGIN_BTN %></button>
<button class="btn"><% languageStrings.REGISTER_BTN %></button>

Using with Json Api’s

Since we configured our localization middleware, we can use it in everywhere in our express.js apps:

app.post("/register", function (req, res) {
    userRepo.register(req.body.email, req.body.password, function(err, result) {
        if(err) {
            res.send(req.languageStrings.REGISTER_ERROR_MSG)
        } else {
            res.send(req.languageStrings.REGISTER_SUCCESS_MSG)
        }
    })
})

The important thing is including our getLanguageStrings middleware in the request pipeline whether by app.use() or route spesific.

Cheers!