fix: use callable .get to detect Headers in pickRequestHost

This commit is contained in:
Linus Rath
2026-07-09 13:51:12 +02:00
parent e933800792
commit 38313639ed
2 changed files with 19 additions and 1 deletions
+10
View File
@@ -111,6 +111,16 @@ describe('pickRequestHost', () => {
it('lower-cases the result', () => {
expect(pickRequestHost(mockHeaders({ host: 'EXAMPLE.com' }))).toBe('example.com');
});
it('handles a ReadonlyHeaders-shaped object with an internal `headers` field', () => {
// `await headers()` returns Next's ReadonlyHeaders, which exposes `.get`
// directly but also carries an internal `headers` property. Ensure we use
// its own `.get` rather than descending into `.headers` (#585).
const readonlyLike = Object.assign(mockHeaders({ host: 'ro.example.com' }), {
headers: { notCallable: true },
});
expect(pickRequestHost(readonlyLike as unknown as Headers)).toBe('ro.example.com');
});
});
describe('matchDomainBranding', () => {
+9 -1
View File
@@ -113,7 +113,15 @@ type HeadersLike = Headers | { get(name: string): string | null };
* host header is set.
*/
export function pickRequestHost(headersOrReq: NextRequest | HeadersLike): string | null {
const headers: HeadersLike = 'headers' in headersOrReq ? (headersOrReq as NextRequest).headers : headersOrReq;
// A Headers / ReadonlyHeaders exposes `.get` directly; a NextRequest carries
// its headers under `.headers`. Discriminate on the callable `.get` rather
// than the presence of a `headers` property, since ReadonlyHeaders (returned
// by `await headers()`) also has an internal `headers` field (#585).
const candidate = headersOrReq as { get?: unknown };
const headers: HeadersLike =
typeof candidate.get === 'function'
? (headersOrReq as HeadersLike)
: (headersOrReq as NextRequest).headers;
const raw = headers.get('x-forwarded-host') || headers.get('host');
if (!raw) return null;
const first = raw.split(',')[0]?.trim();