Skip to content
Myr

Fix headers set to `undefined` in `init` hooks being sent as the string `"undefined"`

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Headers modified by `init` hooks skip the option merging that filters `undefined` values, and the `Headers` constructor turns `undefined` into the string `'undefined'`, so `options.headers.foo = undefined` in an `init` hook sent `foo: undefined` instead of removing the header. Plain header objects are now applied entry by entry so `undefined` deletes the header, matching the documented behavior for `.extend()`. The check for a user-provided `Content-Type` had the same problem: it built a `Headers` instance from the raw header object, so removing the header in an `init` hook counted as providing one and the JSON body was sent without `application/json`. The check now uses the same header merging as the request.

authored by Sindre Sorhus · committed by Sindre Sorhus · parent 50c3810 · Browse files · 3 files+98 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+98 added−2 removed

  • tests:+83 added−1 removed
  • other:+15 added−1 removed

3 files+98 added−2 removed

modified:source/core/Ky.ts+1 added-1 removed
433 unmodified lines
434 this.#options.duplex = 'half';435 }436437 // A `Request` input's headers are already merged in, so only a content-type from `options.headers` counts as user-provided.438 const userProvidedContentType = options.headers && new globalThis.Headers(options.headers as HeadersInit).has('content-type');438 const userProvidedContentType = options.headers !== undefined && mergeHeaders({}, options.headers).has('content-type');439440 if (this.#options.json !== undefined) {441 this.#options.body = this.#options.stringifyJson?.(this.#options.json) ?? JSON.stringify(this.#options.json);442 if (!userProvidedContentType) {
819 unmodified lines
modified:source/utils/merge.ts+14 added
61 unmodified lines
62};6364export const mergeHeaders = (source1: KyHeadersInit = {}, source2: KyHeadersInit = {}) => {65 const result = new globalThis.Headers(source1 as RequestInit['headers']);6667 // The `Headers` constructor would turn an `undefined` value into the string `'undefined'`, so plain objects are applied directly to keep the documented deletion behavior (for example, from `init` hooks).68 if (isPlainObject(source2)) {69 for (const [key, value] of Object.entries(source2)) {70 if (value === undefined) {71 result.delete(key);72 } else {73 result.set(key, value as string);74 }75 }7677 return result;78 }7980 const isHeadersInstance = source2 instanceof globalThis.Headers;81 const source = new globalThis.Headers(source2 as RequestInit['headers']);8283 for (const [key, value] of source.entries()) {
279 unmodified lines
modified:test/headers.ts+83 added-1 removed
12 unmodified lines
13 response.end(JSON.stringify(request.headers));14};1516test.serial('works with nullish headers even in old browsers', async t => {17 // One `Headers` construction while merging headers, plus the two response assertions.17 t.plan(4);18 t.plan(3);1920 const server = await createHttpTestServer(t);21 server.get('/', echoHeaders);22
439 unmodified lines
462463 t.false('rainbow' in response);464 t.true('unicorn' in response);465});466467test('remove header by setting it to undefined in an init hook (inherited from defaults)', async t => {468 const server = await createHttpTestServer(t);469 server.get('/', echoHeaders);470471 const api = ky.create({472 headers: {473 rainbow: 'rainbow',474 unicorn: 'unicorn',475 },476 hooks: {477 init: [478 options => {479 (options.headers as Record<string, string | undefined>)['rainbow'] = undefined;480 },481 ],482 },483 });484485 const response = await api(server.url).json<IncomingHttpHeaders>();486487 t.is(response['unicorn'], 'unicorn');488 t.false('rainbow' in response);489});490491test('remove header by setting it to undefined in an init hook (inherited from a Request input)', async t => {492 const server = await createHttpTestServer(t);493 server.get('/', echoHeaders);494495 const response = await ky(new Request(server.url, {headers: {rainbow: 'rainbow', unicorn: 'unicorn'}}), {496 hooks: {497 init: [498 options => {499 options.headers = {rainbow: undefined};500 },501 ],502 },503 }).json<IncomingHttpHeaders>();504505 t.is(response['unicorn'], 'unicorn');506 t.false('rainbow' in response);507});508509test('init hook headers object with undefined values only sends defined headers', async t => {510 const server = await createHttpTestServer(t);511 server.get('/', echoHeaders);512513 const response = await ky(server.url, {514 hooks: {515 init: [516 options => {517 options.headers = {518 rainbow: undefined,519 unicorn: 'unicorn',520 };521 },522 ],523 },524 }).json<IncomingHttpHeaders>();525526 t.is(response['unicorn'], 'unicorn');527 t.false('rainbow' in response);528});529530test('json option sets `content-type` when an init hook removes the header with undefined', async t => {531 const server = await createHttpTestServer(t);532 server.post('/', echoHeaders);533534 const headers = await ky.post(server.url, {535 json: {foo: true},536 hooks: {537 init: [538 options => {539 options.headers = {'content-type': undefined};540 },541 ],542 },543 }).json<IncomingHttpHeaders>();544545 t.is(headers['content-type'], 'application/json');546});