Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(sdk-js): let a request header replace a default in any case

Yudhi Armyndharis98d22086c825
diff --git a/sdk/javascript/src/http.ts b/sdk/javascript/src/http.ts
index 20edaeaaa..951cebda2 100644
--- a/sdk/javascript/src/http.ts
+++ b/sdk/javascript/src/http.ts
@@ -188,12 +188,14 @@ async function send<T>(
// Auth and JSON content-type WIN over caller-supplied defaults/per-request headers — the SDK only
// ever sends a JSON body, and this matches the Python and PHP SDKs (which force JSON) and the
// documented "JSON headers win" contract. Header names are case-insensitive and fetch joins duplicates,
- // so drop a caller's copy in any case before adding ours; putting ours last is not enough.
- const headers: Record<string, string> = {};
- for (const [name, value] of Object.entries({ ...config.defaultHeaders, ...options.headers })) {
+ // so merge by lowercased name (a per-request header replaces a default in any case) and drop a
+ // caller's copy of ours before adding them; putting ours last is not enough.
+ const merged = new Map<string, [string, string]>();
+ for (const [name, value] of [...Object.entries(config.defaultHeaders), ...Object.entries(options.headers ?? {})]) {
const lower = name.toLowerCase();
- if (lower !== 'content-type' && lower !== 'x-api-key') headers[name] = value;
+ if (lower !== 'content-type' && lower !== 'x-api-key') merged.set(lower, [name, value]);
}
+ const headers: Record<string, string> = Object.fromEntries(merged.values());
headers['Content-Type'] = 'application/json';
headers['X-API-Key'] = config.apiKey;
diff --git a/sdk/javascript/test/client.test.ts b/sdk/javascript/test/client.test.ts
index 3edaaf587..5b2820f2b 100644
--- a/sdk/javascript/test/client.test.ts
+++ b/sdk/javascript/test/client.test.ts
@@ -464,6 +464,23 @@ describe('OpenWAClient', () => {
expect(wire!.get('x-trace')).toBe('keep');
});
+ it('lets a per-request header replace a default header that differs only in case', async () => {
+ let wire: Headers | undefined;
+ const recordingFetch: FetchLike = async (_url, init) => {
+ wire = new Headers(init?.headers);
+ return new Response('[]', { status: 200 });
+ };
+ const c = new OpenWAClient({
+ baseUrl: 'http://localhost',
+ apiKey: 'k',
+ defaultHeaders: { Accept: 'a', 'X-Trace': 'keep' },
+ fetch: recordingFetch,
+ });
+ await c.request({ method: 'GET', path: '/api/sessions', headers: { accept: 'b' } });
+ expect(wire!.get('accept')).toBe('b');
+ expect(wire!.get('x-trace')).toBe('keep');
+ });
+
it('calls the global fetch unbound from the client config when none is injected', async () => {
// Browsers and Workers reject a fetch invoked as a method of another object ("Illegal invocation").
vi.stubGlobal('fetch', function (this: unknown) {