Skip to content
Myr

Fix headers set to `undefined` not removing the header from a `Request` input

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

authored by Sindre Sorhus · committed by Sindre Sorhus · parent 91ea8a9 · Browse files · 8 files+329 added−44 removed
This commit

State

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

Diff stats

8 files+329 added−44 removed

  • tests:+298 added−1 removed
  • other:+31 added−43 removed

8 files+329 added−44 removed

modified:source/core/Ky.ts+1 added-1 removed
1250 unmodified lines
1251 this.#cachedNormalizedOptions = undefined;1252 this.request = request;1253 }12541255 // A replacement `Request` from a hook or `ky.retry({request})` carries its own signal, so re-attach Ky's managed signal to keep timeouts and user aborts working. Request-like objects are used as-is since the `Request` constructor cannot copy them.1255 // A replacement `Request` from a hook or `ky.retry({request})` carries its own signal, so re-attach Ky's managed signal to keep timeouts and user aborts working. Request-like objects are used as-is since the `Request` constructor cannot copy them, so they keep whatever signal they carry, even on a retry after a timeout.1256 #withManagedSignal(request: Request): Request {1257 if (!this.#options.signal || !(request instanceof globalThis.Request)) {1258 return request;1259 }
21 unmodified lines
modified:source/types/hooks.ts+2 added-2 removed
1 unmodified line
2import type {KyRequest, KyResponse} from '../index.js';3import type {NormalizedOptions, Options} from './options.js';45/**6This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here.6This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here. The `headers` option is always a plain object with lowercase names, where a header removed with `undefined` keeps an `undefined` value.78Unlike other hooks, `init` hooks are synchronous. Any error thrown will propagate synchronously and will not be caught by `beforeError` hooks.910@example
75 unmodified lines
86export type AfterResponseHook = (state: AfterResponseState) => Response | RetryMarker | void | Promise<Response | RetryMarker | void>;8788export type Hooks = {89 /**90 This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here.90 This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here. The `headers` option is always a plain object with lowercase names, where a header removed with `undefined` keeps an `undefined` value.9192 Unlike other hooks, `init` hooks are synchronous. Any error thrown will propagate synchronously and will not be caught by `beforeError` hooks.9394 A common use case is to add a search parameter to every request:
276 unmodified lines
modified:source/types/ky.ts+1 added-1 removed
87 unmodified lines
88 Create a new Ky instance with some defaults overridden with your own.8990 In contrast to `ky.create()`, `ky.extend()` inherits defaults from its parent.9192 You can pass headers as a `Headers` instance or a plain object. Plain object header names are normalized to lowercase when options are merged, so `init` hooks always see lowercase keys.92 You can pass headers as a `Headers` instance or a plain object. Headers are normalized to a plain object with lowercase names when options are merged, so `init` hooks always see a plain object with lowercase keys. A header removed with `undefined` stays in that object with an `undefined` value.9394 You can remove a header with `.extend()` by passing the header with an `undefined` value. Passing `undefined` as a string removes the header only if it comes from a `Headers` instance.9596 Similarly, you can remove existing `hooks` entries by extending the hook with an explicit `undefined`.
108 unmodified lines
modified:source/types/options.ts+1 added-1 removed
414 unmodified lines
415416 /**417 HTTP headers used to make the request.418419 You can pass a `Headers` instance or a plain object. Plain object header names are normalized to lowercase when options are merged, so `init` hooks always see lowercase keys.419 You can pass a `Headers` instance or a plain object. Headers are normalized to a plain object with lowercase names when options are merged, so `init` hooks always see a plain object with lowercase keys. A header removed with `undefined` stays in that object with an `undefined` value.420421 You can remove a header with `.extend()` by passing the header with an `undefined` value. Passing `undefined` as a string removes the header only if it comes from a `Headers` instance.422423 @example
71 unmodified lines
modified:source/utils/merge.ts+24 added-36 removed
60 unmodified lines
61 return deepMerge({}, ...sources);62};6364export const mergeHeaders = (source1: KyHeadersInit = {}, source2: KyHeadersInit = {}) => {65 // The base source is copied as-is. Only the second source carries deletion markers: `undefined` in a plain object (for example, from `init` hooks or merged options), or the string `'undefined'` in a `Headers` instance.66 const result = new globalThis.Headers(source1 as RequestInit['headers']);6767 // 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) {68 for (const [key, value] of Object.entries(toHeaderObject(source2))) {69 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()) {84 if ((isHeadersInstance && value === 'undefined') || value === undefined) {70 result.delete(key);71 } else {72 result.set(key, value);73 }
25 unmodified lines
99100 return copy as T;101 }102118 if (value instanceof globalThis.Headers) {119 return new globalThis.Headers(value) as T;120 }121103 if (Array.isArray(value)) {104 return [...value] as T;105 }106
5 unmodified lines
112 return value;113};114115// Header names are case-insensitive, so they are normalized to lowercase (like `Headers` does) so that overrides and `undefined` deletions match regardless of how the name was spelled and `init` hooks can rely on lowercase keys.116// An `undefined` value is kept as a deletion marker so it can still remove a header inherited from a `Request` input when the request is created.135const mergeHeaderObjects = (source1: Record<string, unknown>, source2: Record<string, unknown>): Record<string, string> => {136 const result = new Map<string, string>();117const mergeHeaderObjects = (source1: Record<string, unknown>, source2: Record<string, unknown>): Record<string, string | undefined> => {118 const result = new Map<string, string | undefined>();119120 for (const [key, value] of [...Object.entries(source1), ...Object.entries(source2)]) {139 if (value === undefined) {140 result.delete(key.toLowerCase());141 } else {142 result.set(key.toLowerCase(), value as string);121 result.set(key.toLowerCase(), value as string | undefined);143 }122 }123124 return Object.fromEntries(result);125};126149const mergeHeaderContainers = (source1: KyHeadersInit, source2: KyHeadersInit): KyHeadersInit => {150 if (isPlainObject(source1) && isPlainObject(source2)) {151 return mergeHeaderObjects(source1, source2);127// Every header source is merged as a plain object so deletion markers survive no matter how the headers were provided. A `Headers` instance cannot hold `undefined`, so its string `'undefined'` counts as a deletion. A plain object is returned as-is, so callers must not mutate the result.128const toHeaderObject = (source: KyHeadersInit): Record<string, string | undefined> => {129 if (isPlainObject(source)) {130 return source as Record<string, string | undefined>;131 }132154 return mergeHeaders(source1, source2);133 const isHeadersInstance = source instanceof globalThis.Headers;134 const result: Record<string, string | undefined> = {};135136 // A header named `__proto__` is dropped here, because assigning it sets the prototype instead of an own property. This is too much of an edge case to be worth supporting.137 for (const [key, value] of new globalThis.Headers(source as RequestInit['headers']).entries()) {138 result[key] = isHeadersInstance && value === 'undefined' ? undefined : value;139 }140141 return result;142};143144const mergeHeaderContainers = (source1: KyHeadersInit, source2: KyHeadersInit): Record<string, string | undefined> =>145 mergeHeaderObjects(toHeaderObject(source1), toHeaderObject(source2));146147function newHookValue<K extends keyof Hooks>(original: Hooks, incoming: Hooks, property: K): NormalizedHooks[K] {148 if (Object.hasOwn(incoming, property) && incoming[property] === undefined) {149 return [];150 }
181 unmodified lines
332 // Scoped to the root options level so it never rewrites nested user data that333 // happens to contain a `headers` key (e.g. a `json` request body).334 if (isRoot && isObject((source as any).headers)) {335 const {value: headerValue, isReplace} = getReplaceState((source as any).headers);346 headers = isReplace347 ? cloneShallow(headerValue as KyHeadersInit)348 : mergeHeaderContainers(headers, headerValue as KyHeadersInit);336 headers = mergeHeaderContainers(isReplace ? {} : headers, headerValue as KyHeadersInit);337338 returnValue.headers = headers;339 }340 }
24 unmodified lines
modified:test/headers.ts+296 added
776 unmodified lines
777 }).json<IncomingHttpHeaders>();778779 t.is(headers['content-type'], 'application/json');780});781782test('remove a `Request` input header by setting it to undefined in the request options', async t => {783 const server = await createHttpTestServer(t);784 server.get('/', echoHeaders);785786 const response = await ky(new Request(server.url, {headers: {rainbow: 'rainbow', unicorn: 'unicorn'}}), {787 headers: {rainbow: undefined},788 }).json<IncomingHttpHeaders>();789790 t.is(response['unicorn'], 'unicorn');791 t.false('rainbow' in response);792});793794test('remove a `Request` input header with a differently cased name in the request options', async t => {795 const server = await createHttpTestServer(t);796 server.get('/', echoHeaders);797798 const response = await ky(new Request(server.url, {headers: {'X-Rainbow': 'rainbow', unicorn: 'unicorn'}}), {799 headers: {'x-rainbow': undefined},800 }).json<IncomingHttpHeaders>();801802 t.is(response['unicorn'], 'unicorn');803 t.false('x-rainbow' in response);804});805806test('remove a `Request` input header by setting it to undefined in instance defaults', async t => {807 const server = await createHttpTestServer(t);808 server.get('/', echoHeaders);809810 const instance = ky.create({headers: {rainbow: undefined}});811 const response = await instance(new Request(server.url, {headers: {rainbow: 'rainbow', unicorn: 'unicorn'}})).json<IncomingHttpHeaders>();812813 t.is(response['unicorn'], 'unicorn');814 t.false('rainbow' in response);815});816817test('header removal set to undefined survives extending the instance', async t => {818 const server = await createHttpTestServer(t);819 server.get('/', echoHeaders);820821 const instance = ky.create({headers: {rainbow: undefined}}).extend({headers: {'x-extended': 'yes'}});822 const response = await instance(new Request(server.url, {headers: {rainbow: 'rainbow'}})).json<IncomingHttpHeaders>();823824 t.is(response['x-extended'], 'yes');825 t.false('rainbow' in response);826});827828test('a header set to undefined in instance defaults can be set again in the request options', async t => {829 const server = await createHttpTestServer(t);830 server.get('/', echoHeaders);831832 const instance = ky.create({headers: {rainbow: undefined}});833 const response = await instance(new Request(server.url, {headers: {rainbow: 'rainbow'}}), {834 headers: {rainbow: 'request'},835 }).json<IncomingHttpHeaders>();836837 t.is(response['rainbow'], 'request');838});839840test('a header set to undefined in the request options removes the value from instance defaults and a `Request` input', async t => {841 const server = await createHttpTestServer(t);842 server.get('/', echoHeaders);843844 const instance = ky.create({headers: {rainbow: 'instance', unicorn: 'unicorn'}});845 const response = await instance(new Request(server.url, {headers: {rainbow: 'request'}}), {846 headers: {rainbow: undefined},847 }).json<IncomingHttpHeaders>();848849 t.is(response['unicorn'], 'unicorn');850 t.false('rainbow' in response);851});852853test('headers set to undefined in the request options are not visible to `beforeRequest` hooks', async t => {854 const server = await createHttpTestServer(t);855 server.get('/', echoHeaders);856857 let hookHeaders: string[] | undefined;858 await ky(server.url, {859 headers: {rainbow: undefined, unicorn: 'unicorn'},860 hooks: {861 beforeRequest: [862 ({request, options}) => {863 hookHeaders = [...options.headers.keys(), ...request.headers.keys()];864 },865 ],866 },867 });868869 t.false(hookHeaders!.includes('rainbow'));870 t.true(hookHeaders!.includes('unicorn'));871});872873test('`json` option removes a `content-type` header set to undefined from a `Request` input', async t => {874 const server = await createHttpTestServer(t);875 server.post('/', echoHeaders);876877 const headers = await ky.post(new Request(server.url, {method: 'POST', body: 'text', headers: {'content-type': 'text/custom'}}), {878 json: {foo: true},879 headers: {'content-type': undefined},880 }).json<IncomingHttpHeaders>();881882 t.is(headers['content-type'], 'application/json');883});884885test('remove a `Request` input header with a shortcut method and a plain object', async t => {886 const server = await createHttpTestServer(t);887 server.post('/', echoHeaders);888889 const response = await ky.post(new Request(server.url, {method: 'POST', body: 'text', headers: {'x-token': 'secret'}}), {890 headers: {'x-token': undefined},891 }).json<IncomingHttpHeaders>();892893 t.false('x-token' in response);894 t.is(response['content-type'], 'text/plain;charset=UTF-8');895});896897test('remove the automatic `content-type` of a `Request` input body with undefined', async t => {898 const server = await createHttpTestServer(t);899 server.post('/', echoHeaders);900901 const response = await ky.post(new Request(server.url, {method: 'POST', body: 'text'}), {902 headers: {'content-type': undefined},903 }).json<IncomingHttpHeaders>();904905 t.false('content-type' in response);906});907908test('remove a `Request` input header with the function form of `.extend()`', async t => {909 const server = await createHttpTestServer(t);910 server.get('/', echoHeaders);911912 const instance = ky.create({headers: {'x-parent': 'parent'}}).extend(parentDefaults => ({913 headers: {...parentDefaults.headers as Record<string, string>, rainbow: undefined},914 }));915 const response = await instance(new Request(server.url, {headers: {rainbow: 'rainbow'}})).json<IncomingHttpHeaders>();916917 t.is(response['x-parent'], 'parent');918 t.false('rainbow' in response);919});920921test('remove a `Request` input header with `replaceOption()` headers containing undefined', async t => {922 const server = await createHttpTestServer(t);923 server.get('/', echoHeaders);924925 const instance = ky.create({headers: {'x-parent': 'parent'}}).extend({926 headers: replaceOption({rainbow: undefined, unicorn: 'unicorn'}),927 });928 const response = await instance(new Request(server.url, {headers: {rainbow: 'rainbow'}})).json<IncomingHttpHeaders>();929930 t.false('x-parent' in response);931 t.false('rainbow' in response);932 t.is(response['unicorn'], 'unicorn');933});934935test('an init hook can set a header that was removed with undefined in the request options', async t => {936 const server = await createHttpTestServer(t);937 server.get('/', echoHeaders);938939 const response = await ky(new Request(server.url, {headers: {rainbow: 'rainbow'}}), {940 headers: {rainbow: undefined},941 hooks: {942 init: [943 options => {944 t.is((options.headers as Record<string, string | undefined>)['rainbow'], undefined);945 t.true('rainbow' in (options.headers as Record<string, string | undefined>));946 (options.headers as Record<string, string | undefined>)['rainbow'] = 'from-init';947 },948 ],949 },950 }).json<IncomingHttpHeaders>();951952 t.is(response['rainbow'], 'from-init');953});954955test('headers set to undefined in the request options do not affect other requests of the instance', async t => {956 const server = await createHttpTestServer(t);957 server.get('/', echoHeaders);958959 const instance = ky.create({headers: {rainbow: 'instance'}});960 const first = await instance(server.url, {headers: {rainbow: undefined}}).json<IncomingHttpHeaders>();961 const second = await instance(server.url).json<IncomingHttpHeaders>();962963 t.false('rainbow' in first);964 t.is(second['rainbow'], 'instance');965});966967test('remove a `Request` input header with undefined when instance defaults are a `Headers` instance', async t => {968 const server = await createHttpTestServer(t);969 server.get('/', echoHeaders);970971 const instance = ky.create({headers: new Headers({'x-instance': '1'})});972 const response = await instance(new Request(server.url, {headers: {'x-token': 'secret'}}), {973 headers: {'x-token': undefined},974 }).json<IncomingHttpHeaders>();975976 t.is(response['x-instance'], '1');977 t.false('x-token' in response);978});979980test('remove a `Request` input header with undefined when instance defaults are an array of pairs', async t => {981 const server = await createHttpTestServer(t);982 server.get('/', echoHeaders);983984 const instance = ky.create({headers: [['x-instance', '1']]});985 const response = await instance(new Request(server.url, {headers: {'x-token': 'secret'}}), {986 headers: {'x-token': undefined},987 }).json<IncomingHttpHeaders>();988989 t.is(response['x-instance'], '1');990 t.false('x-token' in response);991});992993test('remove a `Request` input header with a `Headers` instance holding the string "undefined"', async t => {994 const server = await createHttpTestServer(t);995 server.get('/', echoHeaders);996997 const response = await ky(new Request(server.url, {headers: {'x-token': 'secret', unicorn: 'unicorn'}}), {998 // @ts-expect-error Headers does not support undefined values999 headers: new Headers({'x-token': undefined}),1000 }).json<IncomingHttpHeaders>();10011002 t.is(response['unicorn'], 'unicorn');1003 t.false('x-token' in response);1004});10051006test('remove a `Request` input header with undefined when the request headers are a `Headers` instance', async t => {1007 const server = await createHttpTestServer(t);1008 server.get('/', echoHeaders);10091010 const instance = ky.create({headers: {'x-token': undefined}});1011 const response = await instance(new Request(server.url, {headers: {'x-token': 'secret'}}), {1012 headers: new Headers({'x-request': '1'}),1013 }).json<IncomingHttpHeaders>();10141015 t.is(response['x-request'], '1');1016 t.false('x-token' in response);1017});10181019test('`init` hooks receive plain object headers even when a `Headers` instance was passed', async t => {1020 const server = await createHttpTestServer(t);1021 server.get('/', echoHeaders);10221023 let initHeaders: unknown;1024 const response = await ky(server.url, {1025 headers: new Headers({'X-Rainbow': 'rainbow'}),1026 hooks: {1027 init: [1028 options => {1029 initHeaders = options.headers;1030 },1031 ],1032 },1033 }).json<IncomingHttpHeaders>();10341035 t.deepEqual(initHeaders, {'x-rainbow': 'rainbow'});1036 t.is(response['x-rainbow'], 'rainbow');1037});10381039test('a `Request` input header with the literal string "undefined" is sent as-is', async t => {1040 let sentHeaders: string[][] | undefined;10411042 await ky(new Request('https://example.com', {headers: {'x-a': 'undefined', 'x-b': '1'}}), {1043 async fetch(request) {1044 sentHeaders = [...(request as Request).headers];1045 return new Response('ok');1046 },1047 });10481049 t.deepEqual(sentHeaders, [['x-a', 'undefined'], ['x-b', '1']]);1050});10511052test('duplicate `set-cookie` headers on a `Request` input are all sent', async t => {1053 let sentHeaders: string[][] | undefined;1054 const request = new Request('https://example.com');1055 request.headers.append('set-cookie', 'a=1');1056 request.headers.append('set-cookie', 'b=2');10571058 await ky(request, {1059 async fetch(request) {1060 sentHeaders = [...(request as Request).headers];1061 return new Response('ok');1062 },1063 });10641065 t.deepEqual(sentHeaders, [['set-cookie', 'a=1'], ['set-cookie', 'b=2']]);1066});10671068test('`.extend()` callbacks receive plain object headers even when a `Headers` instance was passed', t => {1069 let parentHeaders: unknown;1070 ky.create({headers: new Headers({'X-Rainbow': 'rainbow'})}).extend(parentDefaults => {1071 parentHeaders = parentDefaults.headers;1072 return {};1073 });10741075 t.deepEqual(parentHeaders, {'x-rainbow': 'rainbow'});1076});
modified:test/hooks.ts+2 added-1 removed
5831 unmodified lines
5832 headers: new Headers(),5833 hooks: {5834 init: [5835 options => {5836 (options.headers as Headers).set('x-request-id', String(++requestIdentifier));5836 // Merged headers are always a plain object with lowercase names, even when a `Headers` instance was passed.5837 (options.headers as Record<string, string>)['x-request-id'] = String(++requestIdentifier);5838 },5839 ],5840 },5841 });
129 unmodified lines
modified:readme.md+2 added-2 removed
438 unmodified lines
439440Type: `Function[]`\441Default: `[]`442443This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here.443This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here. The `headers` option is always a plain object with lowercase names, where a header removed with `undefined` keeps an `undefined` value.444445Unlike other hooks, `init` hooks are synchronous. Any error thrown will propagate synchronously and will not be caught by `beforeError` hooks.446447A common use case is to add a search parameter to every request:
481 unmodified lines
929Create a new `ky` instance with some defaults overridden with your own.930931In contrast to `ky.create()`, `ky.extend()` inherits defaults from its parent.932933You can pass headers as a `Headers` instance or a plain object. Plain object header names are normalized to lowercase when options are merged, so `init` hooks always see lowercase keys.933You can pass headers as a `Headers` instance or a plain object. Headers are normalized to a plain object with lowercase names when options are merged, so `init` hooks always see a plain object with lowercase keys. A header removed with `undefined` stays in that object with an `undefined` value.934935You can remove a header with `.extend()` by passing the header with an `undefined` value.936Passing `undefined` as a string removes the header only if it comes from a `Headers` instance.937
919 unmodified lines