javascriptnode.jsytdl

403 Forbidden when using ytdl-core


Recently, I attempted to download a YouTube video using a custom program that uses ytdl-core on NPM. However, after attempting several URLs, I received 403 Forbidden through all of them.

Sample code is below:

import { ytdl } from "ytdl-core";
import * as fs from "node:fs";

// ...

const info = ytdl.getInfo("some-video-id");

const stream = ytdl.downloadFromInfo(info, { filter: 'videoandaudio' });
fs.createWriteStream(`${makeSafe(info.videoDetails.title)}.mp4`);

Solution

  • YouTube recently released an update that breaks most video downloaders. The change implements new requirements that when failed, result in a 403 Forbidden response. Unfortunately, as ytdl-core is no longer actively maintained, it is recommended that you move to @distube/ytdl-core. The maintainers on that package have released a fix in commit 3df824e that patches the issue present here. To move, follow these steps:

    1. Uninstall ytdl-core to prevent conflicting packages with the same name
    npm uninstall ytdl-core
    
    1. Install @distube/ytdl-core at the latest version
    npm install @distube/ytdl-core@latest
    
    1. Replace references of the old package with @distube/ytdl-core

    Anywhere that you use the old ytdl-core package, put the new @distube/ytdl-core package. This can be as simple as rewriting your imports.


    Examples:

    import { ytdl } from "@distube/ytdl-core"; // ESM
    
    const ytdl = require("@distube/ytdl-core"); // CommonJS