Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-preferred-locale-quality-sort.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Fixes `Astro.preferredLocale` and `Astro.preferredLocaleList` ignoring `Accept-Language` quality values when they are absent or `0`. An entry without an explicit `q=` now correctly counts as quality `1.0` (per RFC 7231) and an entry with `q=0` is treated as not acceptable, so the highest-quality locale is selected regardless of header order.
9 changes: 5 additions & 4 deletions packages/astro/src/i18n/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,11 @@ function sortAndFilterLocales(browserLocaleList: BrowserLocale[], locales: Local
return true;
})
.sort((a, b) => {
if (a.qualityValue && b.qualityValue) {
return Math.sign(b.qualityValue - a.qualityValue);
}
return 0;
// An absent `q=` means quality 1.0 (RFC 7231), while a bare `*` defaults
// to 0 so it is never ranked above a real locale.
const qa = a.locale === '*' ? (a.qualityValue ?? 0) : (a.qualityValue ?? 1);
const qb = b.locale === '*' ? (b.qualityValue ?? 0) : (b.qualityValue ?? 1);
return qb - qa;
});
}

Expand Down
14 changes: 14 additions & 0 deletions packages/astro/test/units/i18n/i18n-utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,20 @@ describe('computePreferredLocale', () => {
assert.equal(computePreferredLocale(req, locales), 'fr');
});

it('prefers an implicit q=1 entry over a lower explicit-q entry regardless of header order', () => {
const req = new Request('http://example.com/', {
headers: { 'Accept-Language': 'en;q=0.7, de' },
});
assert.equal(computePreferredLocale(req, ['en', 'fr', 'de']), 'de');
});

it('excludes a q=0 entry from winning', () => {
const req = new Request('http://example.com/', {
headers: { 'Accept-Language': 'de;q=0, en;q=0.5' },
});
assert.equal(computePreferredLocale(req, ['en', 'fr', 'de']), 'en');
});

it('returns undefined when no match', () => {
const req = new Request('http://example.com/', {
headers: { 'Accept-Language': 'de,ja' },
Expand Down
Loading