Oct 3, 2024

Use YouTube.js with a Proxy Service

The code below demonstrates how to use the YouTube.js NPM library with a third-party proxy service, such as Smartproxy, Oxylabs, or Storm Proxies.

import { Platform, Innertube } from "youtubei.js";
import { ProxyAgent } from 'undici';

const proxyAgent = new ProxyAgent(
	`http://ABC123:[email protected]:10001`
);

const youtube = await Innertube.create({
  fetch(input: RequestInfo | URL, init?: RequestInit) {
    return Platform.shim.fetch(input, {
      ...init,
      dispatcher: proxyAgent
    })
  }
});

Futher Info

Node.js v20 or higher is required for this code to work, since native fetch with the dispatcher option was added to Node.js at that version.

Using fetch() to fire off this request will fail since YouTube.js adds a number of headers, etc. to the request before your custom fetch function is called. You need those headers to be present. By using Platform.shim.fetch(), youโ€™re still leveraging Node.jsโ€™ fetch under the hood, with with the necessary headers added to requests.

By instantiating the ProxyAgent class that undici provides and passing in the URL to our proxy, we can create a proxy agent that is compatible with the dispatcher option.

Once this code is in place, you can call methods like await youtube.getInfo(videoId) to fetch YouTube data.