On this page7 sections
For years the answer to "download a YouTube video in Node" was ytdl-core. The original package hasn't had a release since July 2023 (npm, checked 2026-11-20), and anything that reads YouTube directly needs frequent updates to keep working. This guide covers the free route first, why it tends to fail once your app is deployed, and a version that behaves the same in production: a fetch() call, the file streamed to disk or delivered to your bucket, and a Next.js route with a webhook.
The free route: a maintained fork
@distube/ytdl-core is the actively maintained fork (version 5.2.1 was published on 2026-11-04):
npm install @distube/ytdl-coreimport { createWriteStream } from 'node:fs'
import { pipeline } from 'node:stream/promises'
import { Quality, Ytdl } from '@distube/ytdl-core'
const yt = new Ytdl()
const info = await yt.getInfo('https://www.youtube.com/watch?v=jNQXAC9IVRw')
// HD video and audio come as separate streams: download both, then merge with ffmpeg
await pipeline(yt.download(info, { quality: Quality.HighestVideo, filter: { hasVideo: true } }), createWriteStream('video.mp4'))
await pipeline(yt.download(info, { quality: Quality.HighestAudio, filter: { hasAudio: true, hasVideo: false } }), createWriteStream('audio.webm'))Version 5 changed the API from the old ytdl(url) call and needs a recent Node (22.22.2+, 24.15.0+ or 26+), so older tutorials won't run as written.
For a script on your own machine, that's the right answer and it costs nothing. Three things catch people once it's part of a shipped app:
- It breaks on the server. YouTube blocks or challenges a lot of traffic from cloud and datacenter IPs. We ran the code above from a cloud machine on 2026-11-20:
getInfoworked, but the download failed withitag 133: gave up after 3 resumes without progress(SABR session failed). The same kind of code that works from home fails from Vercel, Render, Railway, Fly or AWS. - You merge the streams yourself. YouTube serves video and audio together only at low resolutions, and from that cloud machine it offered no combined format at all for the test video. Getting a normal MP4 with sound means downloading both streams and running ffmpeg on your server.
- It breaks again later. When YouTube changes how it serves video, you wait for the fork to ship a fix, then upgrade and redeploy while downloads are down.
If none of that applies to you (a local script, a small internal tool), keep the fork.
The same thing with one API call
Importly takes the YouTube link and returns a link to the finished file, video and audio already in one MP4, at the quality you ask for. It works the same from a server as from your laptop, and Node 18 and later have fetch built in:
// download.mjs
const API = 'https://api.importly.io'
const headers = {
Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}`,
'Content-Type': 'application/json',
}
export async function importVideo(url, options = {}) {
const res = await fetch(`${API}/import`, {
method: 'POST',
headers,
body: JSON.stringify({
url,
videoQuality: '1080p', // a ceiling: the best stream at or below it
maxCostDollars: 1, // fail instead of downloading something huge
...options, // e.g. includeVideo: false for audio only, webhookUrl, store: true
}),
})
const body = await res.json()
// The request itself was rejected: bad link, bad key, low balance, rate limit
if (!res.ok) throw new ImportError(body.code, body.error, res.status, body.retryAfter)
return body.data.jobId
}
export async function waitForImport(jobId) {
for (let polls = 0; polls < 200; polls++) {
const res = await fetch(`${API}/import/status?id=${jobId}`, { headers })
const body = await res.json()
if (!res.ok) throw new ImportError(body.code, body.error, res.status, body.retryAfter)
const { status, result, code, message } = body.data
if (status === 'completed') return result // { mediaUrl, title, duration, filename, ... }
if (status === 'failed') throw new ImportError(code, message)
await new Promise((resolve) => setTimeout(resolve, 3000))
}
throw new ImportError('TIMEOUT', `Import ${jobId} still running`)
}
export class ImportError extends Error {
constructor(code, message, status, retryAfter) {
super(message)
this.code = code
this.status = status
this.retryAfter = retryAfter
}
}Then save the file, from a worker or a script:
import fs from 'node:fs'
import { Readable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import { importVideo, waitForImport } from './download.mjs'
const jobId = await importVideo('https://www.youtube.com/watch?v=jNQXAC9IVRw')
const { mediaUrl, filename } = await waitForImport(jobId)
const file = await fetch(mediaUrl)
await pipeline(Readable.fromWeb(file.body), fs.createWriteStream(filename))mediaUrl is a signed link that lasts 7 days, so copy the file somewhere permanent. To skip that step, connect your own S3, R2 or B2 bucket once and send store: true: the file lands in your bucket and never passes through your server. See S3 storage.
Handle errors by code
Failed jobs and rejected requests both carry a code:
switch (err.code) {
case 'VIDEO_PRIVATE':
case 'VIDEO_UNAVAILABLE':
case 'GEO_BLOCKED':
return showUser('That video can\'t be downloaded. Is it public?')
case 'LIVE_NOT_SUPPORTED':
return showUser('Live streams can be downloaded once they end.')
case 'INVALID_URL':
case 'PLAYLIST_NOT_SUPPORTED':
return showUser('Paste a link to a single video.')
case 'MAX_COST_EXCEEDED':
case 'FILE_TOO_LARGE':
return showUser('That video is too long. Try a lower quality.')
case 'SOURCE_THROTTLED':
case 'RATE_LIMITED':
return retryLater(url, err.retryAfter) // a retry a little later usually works
default:
throw err // INSUFFICIENT_BALANCE, UNAUTHORIZED, INTERNAL_ERROR: alert yourself
}Failed imports aren't charged (except FILE_TOO_LARGE, which pays for what was downloaded before your balance ran out). The full list is on Errors & rate limits.
A Next.js route with a webhook
Downloads can take longer than a serverless function should wait, so in an app, start the job in one route and receive the result in another:
// app/api/import/route.js
import { importVideo, ImportError } from '@/lib/download.mjs'
export async function POST(request) {
const { url } = await request.json()
try {
const jobId = await importVideo(url, { webhookUrl: 'https://example.com/api/import/webhook' })
// save jobId against the user's record here
return Response.json({ jobId })
} catch (err) {
if (err instanceof ImportError) return Response.json({ code: err.code, error: err.message }, { status: 422 })
throw err
}
}// app/api/import/webhook/route.js
import { waitForImport } from '@/lib/download.mjs'
export async function POST(request) {
const { data } = await request.json()
// Confirm with the API instead of trusting the payload: returns the result or throws the failure
const result = await waitForImport(data.jobId).catch((err) => ({ error: err.code }))
// update the record for data.jobId with result.mediaUrl, or show result.error to the user
return new Response(null, { status: 204 })
}The webhook sends one POST when the job finishes, with success: false and the code if it failed. Deliveries aren't retried, so poll jobs you haven't heard back about as a fallback. See webhooks.
What it costs
- Downloads are $0.002 per MB downloaded, with a $0.01 minimum per import. A 3-minute video at 720p is about $0.08; a 10-minute one about $0.15.
maxCostDollarscaps each import,includeVideo: falsegets audio only for much less, and failed imports are free.
It's free to try, no card required. See pricing.
Have your coding agent wire it in
Connect https://mcp.importly.io/mcp to Claude Code, Cursor or another coding agent and ask it to add YouTube downloads to your Node app. It gets working code for your stack, writes the integration and tests real calls with your API key. The steps are in Have your agent build Importly into your app.
FAQ
Is ytdl-core still maintained?
The original ytdl-core package's last release was 4.11.5 in July 2023. @distube/ytdl-core is the maintained fork and still ships updates.
Why does my YouTube download work locally but fail on my server?
YouTube blocks or challenges a lot of traffic from cloud and datacenter IPs, so code that works from a home connection fails from Vercel, Render, Railway or AWS. It's the server's network, not your code.
How do I get 1080p with audio in Node.js?
With a library, download the video and audio streams separately and merge them with ffmpeg. With Importly, send "videoQuality": "1080p" and you get one MP4 with both.
Can I get the transcript too?
Yes. Add "includeTranscript": true to the import and the result includes a timestamped transcript. For transcripts alone, see YouTube transcripts in Node.js.
Related: YouTube downloader API, Video downloader API, Upload a video from a URL to S3, YouTube transcripts in Node.js.