Loading...
const header = req.headers['accept-language'];
const lang = header.slice(0, 2);const header = req.headers['accept-language'] ?? '';
const prefs = header.split(',')
.map((part) => part.trim().split(';q='))
.sort((a, b) => Number(b[1] ?? 1) - Number(a[1] ?? 1))
.map(([tag]) => tag.split('-')[0]);
const lang = req.cookies.lang ?? prefs.find((l) => SUPPORTED.includes(l)) ?? 'en';The header may be missing and holds a weighted list; a saved user choice wins, then the best supported match, then a default.
It is a weight from 0 to 1 that ranks the preference. Languages without q have weight 1, so the list is ordered from most to least preferred.
Use navigator.languages, which returns the same ordered list the browser sends in the header.
Yes, when the content depends on the header. Without it, a cache can serve one language to everyone.