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 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).