Skip to content

Commit

Permalink
Add feature to specify custom headers for proxies (nodejs#1877)
Browse files Browse the repository at this point in the history
  • Loading branch information
Sebmaster authored and crysmags committed Feb 27, 2024
1 parent cfb0a00 commit df90e08
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/proxy-agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class ProxyAgent extends DispatcherBase {

this[kRequestTls] = opts.requestTls
this[kProxyTls] = opts.proxyTls
this[kProxyHeaders] = {}
this[kProxyHeaders] = opts.headers || {}

if (opts.auth && opts.token) {
throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token')
Expand Down
33 changes: 33 additions & 0 deletions test/proxy-agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,39 @@ test('use proxy-agent with token', async (t) => {
proxyAgent.close()
})

test('use proxy-agent with custom headers', async (t) => {
t.plan(2)
const server = await buildServer()
const proxy = await buildProxy()

const serverUrl = `http://localhost:${server.address().port}`
const proxyUrl = `http://localhost:${proxy.address().port}`
const proxyAgent = new ProxyAgent({
uri: proxyUrl,
headers: {
'User-Agent': 'Foobar/1.0.0'
}
})

proxy.on('connect', (req) => {
t.equal(req.headers['user-agent'], 'Foobar/1.0.0')
})

server.on('request', (req, res) => {
t.equal(req.headers['user-agent'], 'BarBaz/1.0.0')
res.end()
})

await request(serverUrl + '/hello?foo=bar', {
headers: { 'user-agent': 'BarBaz/1.0.0' },
dispatcher: proxyAgent
})

server.close()
proxy.close()
proxyAgent.close()
})

test('sending proxy-authorization in request headers should throw', async (t) => {
t.plan(3)
const server = await buildServer()
Expand Down
3 changes: 3 additions & 0 deletions types/proxy-agent.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { IncomingHttpHeaders } from 'http'

import Agent from './agent'
import buildConnector from './connector';
import Dispatcher from './dispatcher'
Expand All @@ -19,6 +21,7 @@ declare namespace ProxyAgent {
*/
auth?: string;
token?: string;
headers?: IncomingHttpHeaders;
requestTls?: buildConnector.BuildOptions;
proxyTls?: buildConnector.BuildOptions;
}
Expand Down

0 comments on commit df90e08

Please sign in to comment.