How can I get the browser language in node.js (express.js)?
Javascriptnode.jsExpressJavascript Problem Overview
User requests some page and I want to know (on server side) what is the language in his/her browser. So I could render template with the right messages.
On client side it's easy:
var language = window.navigator.userLanguage || window.navigator.language
Javascript Solutions
Solution 1 - Javascript
You can use req.headers["accept-language"] to get the language/locale the user has set in his browser.
For easier support, you may want to look into a https://github.com/jed/locale">locale module.
Solution 2 - Javascript
request.acceptsLanguages
will contain a parsed version of request.headers['accept-language']
.
Solution 3 - Javascript
With Express 4.x, you can use the build in req.acceptsLanguages(lang [, ...]) to check if certain languages are accepted.
var express = require('express');
app.get('/translation', function(request, response) {
var lang = request.acceptsLanguages('fr', 'es', 'en');
if (lang) {
console.log('The first accepted of [fr, es, en] is: ' + lang);
...
} else {
console.log('None of [fr, es, en] is accepted');
...
}
});
To get the list of all accepted languages, using Express 4.x, you can use the module accepts.
var express = require('express'), accepts = require('accepts');
app.get('/translation', function(request, response) {
console.log(accepts(request).languages());
...
});
Solution 4 - Javascript
Middleware to set the request language and use it globally:
// place this middleware before declaring any routes
app.use((req, res, next) => {
// This reads the accept-language header
// and returns the language if found or false if not
const lang = req.acceptsLanguages('bg', 'en')
if (lang) { // if found, attach it as property to the request
req.lang = lang
} else { // else set the default language
req.lang = 'en'
}
next()
})
Now you can access 'req.lang'
app.get('/', (req, res) => {
res.send(`The request language is '${req.lang}'`)
})
Example using translation
const translate = {
en: {
helloWorld: "Hello World!"
},
bg: {
helloWorld: "Здравей Свят!"
}
}
app.get('/hello-world', (req, res) => {
res.send(translate[req.lang].helloWorld)
})
Solution 5 - Javascript
You would need to parse the string in req.headers["accept-language"]
. Which will give you a priority list of preferred languages from the client. You can also check req.acceptsLanguages(lang [, ...])
if your language is supported or not.
I would strongly recommend to use [express-request-language][1] to do any language matching work, since it could be very difficult to get it right at the first time.
Most of the time, matching a language is not enough. A user might want to change a preferred language. express-request-language
help you store a preferred language in a cookie it also gives your server a URL path to change a preferred language.
All above functionality can be done with just a couple of lines of code:
app.use(requestLanguage({
languages: ['en-US', 'zh-CN'],
cookie: {
name: 'language',
options: { maxAge: 24*3600*1000 },
url: '/languages/{language}'
}
}));
In case of no match, the middleware will also match a default language (en-US
above).
[1]: https://github.com/tinganho/express-request-language