1 // Select a language based on browser preferences, or cookie
2 module
.exports = function(req
, res
)
4 // If preferred language already set:
5 if (!!req
.cookies
["lang"])
6 return req
.cookies
["lang"];
8 // Else: search and set it
9 const supportedLang
= ["en","es","fr"];
10 const langString
= req
.headers
["accept-language"];
11 let langArray
= langString
12 .replace(/;q=[0-9.]+/g, "") //priority
13 .replace(/-[A-Z]+/g, "") //region (skipped for now...)
14 .split(",") //may have some duplicates, but removal is too costly
15 let bestLang
= "en"; //default: English
16 for (let lang
of langArray
)
18 if (supportedLang
.includes(lang
))
24 // Cookie expires in 183 days (expressed in milliseconds)
25 res
.cookie('lang', bestLang
, { maxAge: 183*24*3600*1000 });