Skip to content

Commit 59a3893

Browse files
committed
Attach X-MS-USER-ID for XHR-based Meilisearch requests
1 parent 0c572ba commit 59a3893

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

docusaurus/src/theme/SearchBar/index.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,32 @@ function SearchBarContent() {
120120
};
121121
}
122122

123+
// Also patch XMLHttpRequest for libraries that use XHR under the hood
124+
const originalXHROpen = (typeof XMLHttpRequest !== 'undefined' && XMLHttpRequest.prototype.open) ? XMLHttpRequest.prototype.open : null;
125+
const originalXHRSend = (typeof XMLHttpRequest !== 'undefined' && XMLHttpRequest.prototype.send) ? XMLHttpRequest.prototype.send : null;
126+
let xhrPatched = false;
127+
if (originalXHROpen && originalXHRSend) {
128+
try {
129+
XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
130+
try { this.__ms_url = url; } catch {}
131+
return originalXHROpen.apply(this, arguments);
132+
};
133+
XMLHttpRequest.prototype.send = function(body) {
134+
try {
135+
if (userId && this && typeof this.setRequestHeader === 'function') {
136+
const url = this.__ms_url || '';
137+
if (shouldAttachUserIdHeader(url)) {
138+
// Only set if not already set
139+
try { this.setRequestHeader('X-MS-USER-ID', userId); } catch {}
140+
}
141+
}
142+
} catch {}
143+
return originalXHRSend.apply(this, arguments);
144+
};
145+
xhrPatched = true;
146+
} catch {}
147+
}
148+
123149
if (searchInstanceRef.current) {
124150
searchInstanceRef.current.destroy?.();
125151
searchInstanceRef.current = null;
@@ -237,6 +263,12 @@ function SearchBarContent() {
237263
} catch {}
238264
originalFetchRef.current = null;
239265
}
266+
if (xhrPatched && originalXHROpen && originalXHRSend) {
267+
try {
268+
XMLHttpRequest.prototype.open = originalXHROpen;
269+
XMLHttpRequest.prototype.send = originalXHRSend;
270+
} catch {}
271+
}
240272
if (searchInstanceRef.current) {
241273
searchInstanceRef.current.destroy?.();
242274
searchInstanceRef.current = null;

0 commit comments

Comments
 (0)