ExpressJS multilanguage: handling multiple languages with route parameters

To enable multilanguage support in ExpressJS we have to define how our application handles route parameters.

We can use the following parameter:


which matches a two-letters language code and it's made optional by the ? modifier. An example:

'use strict';

const app = require('expresss')();
const locales = require('./lib/i18n');

app.get('/:lang([a-z]{2})?', (req, res) => {
    let lang = req.params.lang;
    if(locales.hasOwnProperty(lang)) {
      let locale = locales[lang];
      // Passing the current locale to the view

The above route matches site.tld, site.tld/en or site.tld/de. We can define our locales as follows:

'use strict';

module.exports = {
    it: {
      title: 'Ciao mondo'
    en: {
       title: 'Hello world'
    de: {
        title: 'Hallo Welt'

Prev Articles Next