Skip to content

Commit 7f60f52

Browse files
committed
Intercept global fetch in Node 18.2.0+
While global fetch was supported in Node 18, it was impossible to use with proxies until 18.2.0. From this point onwards, it is usable as long as you use a separate Undici dependency to do that configuration.
1 parent 849eec5 commit 7f60f52

File tree

4 files changed

+32
-2
lines changed

4 files changed

+32
-2
lines changed

overrides/js/package-lock.json

Lines changed: 15 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

overrides/js/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
"license": "AGPL-3.0-or-later",
66
"dependencies": {
77
"global-agent": "3.0.0",
8-
"global-tunnel-ng": "2.7.1"
8+
"global-tunnel-ng": "2.7.1",
9+
"undici": "^5.2.0"
910
}
1011
}

overrides/js/prepend-node.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,4 +112,13 @@ if (MAJOR_NODEJS_VERSION >= 10) {
112112
// `global-tunnel-ng` works only with Node.js v10 and below.
113113
const globalTunnel = require('global-tunnel-ng');
114114
globalTunnel.initialize();
115+
}
116+
117+
if (MAJOR_NODEJS_VERSION >= 18 || global.fetch) {
118+
// Node 18 enables fetch by default (available previously behind a flag). This does not use
119+
// the existing agent API, so is not intercepted by global-agent. Instead, the only way to
120+
// set the HTTP proxy is to separately import Undici (used internally by Node) and configure
121+
// Undici's global proxy agent. We bundle our own Undici dep so we can do this reliably,
122+
// and here we import it to trigger the Undici setup hook defined above.
123+
require('undici');
115124
}

test/fixtures/terminal/js-test-script.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,12 @@ require('http').get('http://example.test/js/http');
55
require('https').get('https://example.test/js/https');
66

77
function sendRequestsTo(baseUrl) {
8+
if (global.fetch) {
9+
// Only in Node 18+ so this isn't actually covered by unit tests, but
10+
// it's useful for manually testing.
11+
fetch(baseUrl + '/global-fetch');
12+
}
13+
814
require('request').get(baseUrl + '/request');
915
require('axios').get(baseUrl + '/axios');
1016
require('superagent').get(baseUrl + '/superagent').end(() => {});

0 commit comments

Comments
 (0)