How to maintain changing state of language in expressJS How to maintain changing state of language in expressJS express express

How to maintain changing state of language in expressJS


I recommend you Lingua for ExpressJS

Basically, Lingua is a middleware for the Express.js and that helps you to internationalise your webapp easily. It determines the language of the user agent and pushes the i18n resources to your views.

$ npm install -s lingua

var express = require('express'),    lingua  = require('lingua');// Express app configuration code and lingua init.app.configure(function() {app.set('views', __dirname + '/views');app.set('view engine', 'ejs');// Lingua configurationapp.use(lingua(app, {    defaultLocale: 'en',    path: __dirname + '/i18n'}));app.use(express.bodyParser());app.use(express.methodOverride());app.use(express.static(__dirname + '/public'));app.use(app.router);

Language files

'./i18n/en.json' and './i18n/de-de.json').// en.json    {        "title": "Hello World",        "content": {            "description": "A little description."        }    }// de-de.json    {        "title": "Hallo Welt",        "content": {            "description": "Eine kleine Beschreibung."        }    }

And you can easily implement it on your pages with:

<h1><%= lingua.title %></h1> <!-- out: <h1>Hello World</h1> --><p><%= lingua.content.description %></h1> <!-- out: <p>A little description.</p> -->


On clientside if you are able to set an item on local storage then you are also able to get the same item and use its value to push it to the querystring as well. So you basically need an additional function on your client javascript that will get the item everytime the page opens.

    function getParameterByName(name, url) {        if (!url) url = window.location.href;        name = name.replace(/[\[\]]/g, '\\$&');        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),            results = regex.exec(url);        if (!results) return null;        if (!results[2]) return '';        return decodeURIComponent(results[2].replace(/\+/g, ' '));    }    function checkLanguageFromLocalStorage(){        var clang = getParameterByName('clang');        if (clang == null) {            if (localStorage.getItem("clang") != null) {                var clang = localStorage.getItem("clang");                var url = window.location.href;                url = url.split("?")[0];                url += '?clang='+clang;                window.location.href = url;            }        }    }    checkLanguageFromLocalStorage();


Why don't you pass a cookie with the language instead of query parameter? i18n-express has an option called cookieLangName which you have allready configured on the server side (cookieLangName: 'ulang'). Setting cookieLangName makes i18n-express read language from the cookie with the name you pass. All you need is to set this cookie in you client side script - inside changeLanguage function - and it will do the trick:

function changeLanguage(event){   $('#languages img').attr('src','/images/flag-icons/'+event.id+'.png');   document.cookie = `ulang=${event.id}; path=/`;   localStorage.setItem("ulang", `ulang=${event.id}; path=/`); // you can still save it to localStorage and synchronize it when cookie is removed}