diff --git a/middleware/detect-language.js b/middleware/detect-language.js index aaea38f2966e..1d222ede5bd9 100644 --- a/middleware/detect-language.js +++ b/middleware/detect-language.js @@ -36,7 +36,7 @@ function getUserLanguage(browserLanguages) { // 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) + const maybeLanguage = (path.split('/')[path.startsWith('/_next/data/') ? 4 : 1] || '').slice(0, 2) return languageCodes.includes(maybeLanguage) ? maybeLanguage : 'en' } diff --git a/tests/unit/detect-language.js b/tests/unit/detect-language.js index 90cb9462ffb2..e39d15e0e8a6 100644 --- a/tests/unit/detect-language.js +++ b/tests/unit/detect-language.js @@ -6,6 +6,10 @@ describe('detect-language - getLanguageCodeFromPath', () => { expect(getLanguageCodeFromPath('/_next/data/development/ja/articles/foo')).toBe('ja') }) + test('should not error on /_next/data/ input', () => { + expect(getLanguageCodeFromPath('/_next/data/')).toBe('en') + }) + test('should return for paths with an extension', () => { expect(getLanguageCodeFromPath('/ja.json')).toBe('ja') expect(getLanguageCodeFromPath('/_next/data/development/ja.json')).toBe('ja')