How to use authenticated proxies with undici

Viewed 496

Hello so am trying to use undici with a proxy but it doesn't work i tired this

const client = new Client({
  url: 'www.google.com',
  proxy: 'http://user:pass@host:port'
})

as well as this

const { HttpsProxyAgent } = require("https-proxy-agent");
const proxy = new HttpsProxyAgent("http://user:pass@host:port");
time = new Date()
client.request({
  path: '/',
  method: 'GET',
  httpsAgent: proxy 
},

but nothing seems to work

1 Answers

See this link here: https://github.com/nodejs/undici/blob/01302e6d2b2629cca4ad9327abe0f7a317f8399f/docs/best-practices/proxy.md#connect-with-authentication

import { Client } from 'undici'
import { createServer } from 'http'
import proxy from 'proxy'

const server = await buildServer()
const proxy = await buildProxy()

const serverUrl = `http://localhost:${server.address().port}`
const proxyUrl = `http://localhost:${proxy.address().port}`

proxy.authenticate = function (req, fn) {
  fn(null, req.headers['proxy-authorization'] === `Basic ${Buffer.from('user:pass').toString('base64')}`)
}

server.on('request', (req, res) => {
  console.log(req.url) // '/hello?foo=bar'
  res.setHeader('content-type', 'application/json')
  res.end(JSON.stringify({ hello: 'world' }))
})

const client = new Client(proxyUrl)

const response = await client.request({
  method: 'GET',
  path: serverUrl + '/hello?foo=bar',
  headers: {
    'proxy-authorization': `Basic ${Buffer.from('user:pass').toString('base64')}`
  }
})

response.body.setEncoding('utf8')
let data = ''
for await (const chunk of response.body) {
  data += chunk
}
console.log(response.statusCode) // 200
console.log(JSON.parse(data)) // { hello: 'world' }

server.close()
proxy.close()
client.close()

function buildServer () {
  return new Promise((resolve, reject) => {
    const server = createServer()
    server.listen(0, () => resolve(server))
  })
}

function buildProxy () {
  return new Promise((resolve, reject) => {
    const server = proxy(createServer())
    server.listen(0, () => resolve(server))
  })
}
Related