1
0
mirror of synced 2025-12-21 10:57:10 -05:00

fix: detect-language correctly handles root path, add unit tests (#22404)

This commit is contained in:
Mike Surowiec
2021-10-25 20:22:25 -07:00
committed by GitHub
parent 6112336e40
commit bede852dc4
2 changed files with 25 additions and 8 deletions

View File

@@ -34,15 +34,14 @@ function getUserLanguage(browserLanguages) {
}
}
export default function detectLanguage(req, res, next) {
// determine language code from the URL, or default to English
// /en/articles/foo
// ^^
// /_next/data/development/en/articles/foo
// ^^
const maybeLanguage = req.path.split('/')[req.path.startsWith('/_next/data/') ? 4 : 1]
// determine language code from a path. Default to en if no valid match
export function getLanguageCodeFromPath(path) {
const maybeLanguage = path.split('/')[path.startsWith('/_next/data/') ? 4 : 1].slice(0, 2)
return languageCodes.includes(maybeLanguage) ? maybeLanguage : 'en'
}
req.language = languageCodes.includes(maybeLanguage) ? maybeLanguage : 'en'
export default function detectLanguage(req, res, next) {
req.language = getLanguageCodeFromPath(req.path)
// Detecting browser language by user preference
const browserLanguages = parser.parse(req.headers['accept-language'])
req.userLanguage = getUserLanguage(browserLanguages)