How can I get the browser language in node.js (express.js)?

Viewed 66105

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
5 Answers

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)
})
Related