diff --git a/middleware/detect-language.js b/middleware/detect-language.js index a55dfee51b04..aaea38f2966e 100644 --- a/middleware/detect-language.js +++ b/middleware/detect-language.js @@ -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) diff --git a/tests/unit/detect-language.js b/tests/unit/detect-language.js new file mode 100644 index 000000000000..90cb9462ffb2 --- /dev/null +++ b/tests/unit/detect-language.js @@ -0,0 +1,18 @@ +import { expect } from '@jest/globals' +import { getLanguageCodeFromPath } from '../../middleware/detect-language.js' + +describe('detect-language - getLanguageCodeFromPath', () => { + test('should handle client-side routing path shape', () => { + expect(getLanguageCodeFromPath('/_next/data/development/ja/articles/foo')).toBe('ja') + }) + + test('should return for paths with an extension', () => { + expect(getLanguageCodeFromPath('/ja.json')).toBe('ja') + expect(getLanguageCodeFromPath('/_next/data/development/ja.json')).toBe('ja') + }) + + test('should return en for invalid languages', () => { + expect(getLanguageCodeFromPath('/xx/articles/foo')).toBe('en') + expect(getLanguageCodeFromPath('/_next/data/development/xx/articles/foo')).toBe('en') + }) +})