DEV Community

mktoho
mktoho

Posted on • Updated on

How to use authenticated proxy with Node's fetch

fetch in node

The fetch API is now available in node18. However, I was having trouble figuring out how to use a proxy.

Finally, we were able to use fetch through a proxy with the following code.

import { ProxyAgent, setGlobalDispatcher } from "undici"
import { Base64 } from "js-base64"

const agent = new ProxyAgent({
  uri: "http://yout-proxy-host:8080",
  auth: Base64.encode("username:password"),
})

setGlobalDispatcher(agent)

const main = async () => {
  const response = await fetch("https://api.example.com/super-cool-api")
  const json = await response.json()
  console.log(json)
}

main()
Enter fullscreen mode Exit fullscreen mode

I am not good at English so I leave you only with the successful code ๐ŸŽฎ

Top comments (0)