BlogImplementation Guide

YouTube Transcripts in Node.js That Keep Working After You Deploy

Node transcript libraries work on your laptop and fail on Vercel, Render or AWS. A fetch() version with error handling by code and a Next.js route that behaves the same in production.

On this page8 sections

You add YouTube transcripts to a Node app, it works on your laptop, and then it breaks the day it goes to Vercel, Render, Railway, Fly or AWS. That pattern is common enough that it's the main thing people ask about on the issue trackers of the Node transcript libraries. This guide covers the free route first, why it tends to fail once deployed, and a version that behaves the same in production: a plain fetch() call, error handling by code, and a Next.js route you can drop in.

The free route: a transcript library

The quickest start is an npm package such as youtube-transcript:

bash
npm install youtube-transcript
javascript
import { YoutubeTranscript } from 'youtube-transcript'

const segments = await YoutubeTranscript.fetchTranscript('https://www.youtube.com/watch?v=jNQXAC9IVRw')
// [{ text, offset, duration, lang }, ...]
console.log(segments.map((s) => s.text).join(' '))

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. The same call that works from home fails from a Vercel function or a container, and the error it throws often doesn't point at the real cause.
  • No captions, no transcript. Plenty of videos have no caption track at all. The library can only return captions that exist, so you need a speech-to-text fallback with its own download and audio step.
  • It breaks again later. These libraries read YouTube's own pages and internal endpoints. When YouTube changes them, you're waiting on a new release while your feature is down.

If none of that applies to you (a local script, a small internal tool), keep the library.

The same thing with one API call

Importly takes the YouTube link and returns the transcript. It uses the video's captions when there are some, runs speech-to-text when there aren't, and works the same from a server as from your laptop. Node 18 and later have fetch built in, so there's nothing to install:

javascript
// transcript.mjs
const API = 'https://api.importly.io'

export async function getTranscript(url) {
  const res = await fetch(`${API}/transcribe`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      url,
      mode: 'auto', // captions if the video has them, speech-to-text if not
      wait: true, // hold the request until the transcript is ready (up to 30s)
      maxCostDollars: 0.5, // fail instead of running over this on a long video
    }),
  })
  const body = await res.json()

  // The request itself was rejected: bad link, bad key, low balance, rate limit
  if (!res.ok) throw new TranscriptError(body.code, body.error, res.status, body.retryAfter)

  return finish(body.data)
}

async function finish(data, polls = 0) {
  if (data.status === 'completed') return data.result
  if (data.status === 'failed') throw new TranscriptError(data.code, data.message)
  if (polls >= 100) throw new TranscriptError('TIMEOUT', `Job ${data.jobId} still running`)

  // Still running after the wait (long video with no captions): poll every 3s
  await new Promise((resolve) => setTimeout(resolve, 3000))
  const res = await fetch(`${API}/transcribe/status?id=${data.jobId}`, {
    headers: { Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}` },
  })
  const body = await res.json()
  if (!res.ok) throw new TranscriptError(body.code, body.error, res.status, body.retryAfter)
  return finish(body.data, polls + 1)
}

export class TranscriptError extends Error {
  constructor(code, message, status, retryAfter) {
    super(message)
    this.code = code
    this.status = status
    this.retryAfter = retryAfter
  }
}

The result has the whole text and timestamped segments, in the same shape whether it came from captions or speech-to-text:

json
{
  "text": "All right, so here we are, in front of the elephants\n...",
  "source": "platform_captions",
  "captionKind": "manual",
  "language": "en",
  "duration": 19,
  "data": {
    "segments": [
      { "start": 1.2, "end": 3.36, "text": "All right, so here we are, in front of the elephants" }
    ]
  },
  "costInDollars": 0.003
}

source is platform_captions for captions and importly for speech-to-text; captionKind says whether the captions were uploaded (manual) or generated by YouTube (auto). The full field list is in the transcripts docs.

Handle errors by code

Every error has a code and a documentationUrl, so you can branch on the code instead of parsing messages:

javascript
import { getTranscript, TranscriptError } from './transcript.mjs'

try {
  const transcript = await getTranscript(url)
  return transcript.text
} catch (err) {
  if (!(err instanceof TranscriptError)) throw err
  switch (err.code) {
    case 'VIDEO_PRIVATE':
    case 'VIDEO_UNAVAILABLE':
    case 'GEO_BLOCKED':
    case 'LIVE_NOT_SUPPORTED':
      return showUser('That video can\'t be transcribed. Is it public?')
    case 'INVALID_URL':
    case 'PLAYLIST_NOT_SUPPORTED':
      return showUser('Paste a link to a single video.')
    case 'MAX_COST_EXCEEDED':
      return showUser('That video is too long for this feature.')
    case 'SOURCE_THROTTLED':
      return retryLater(url) // refused for a moment; a retry usually works
    case 'RATE_LIMITED':
      return retryLater(url, err.retryAfter)
    default:
      throw err // INSUFFICIENT_BALANCE, UNAUTHORIZED, INTERNAL_ERROR: alert yourself
  }
}

Failed transcriptions are refunded, so a private or removed video costs you nothing. The full list is on Errors & rate limits.

A Next.js API route

The same function works in a route handler. maxDuration gives the function time to wait for the transcript; if your plan caps functions below 30 seconds, drop wait and use a webhook instead (below).

javascript
// app/api/transcript/route.js
import { getTranscript, TranscriptError } from '@/lib/transcript.mjs'

export const maxDuration = 60

export async function POST(request) {
  const { url } = await request.json()
  try {
    const transcript = await getTranscript(url)
    return Response.json({ text: transcript.text, segments: transcript.data.segments })
  } catch (err) {
    if (err instanceof TranscriptError) {
      return Response.json({ code: err.code, error: err.message }, { status: 422 })
    }
    throw err
  }
}

Keep IMPORTLY_API_KEY in your host's environment variables, never in client code: the browser calls your route, and your route calls Importly.

Many videos, or long ones: use a webhook

For a batch, or videos long enough to need speech-to-text, send webhookUrl instead of wait. The request returns a jobId right away, and Importly posts the finished transcript (or the failure, with its code) to your endpoint. In the webhook the transcript fields sit directly on data (data.text, data.data.segments). See webhooks.

What it costs

  • From captions, uploaded or auto-generated: $0.003 per video.
  • Speech-to-text, when a video has no captions: $0.01 per media minute, fetching included, with a $0.01 minimum.
  • maxCostDollars caps each request, and failed transcriptions are refunded.

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 transcripts 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

How do I get a YouTube transcript in Node.js?

For a local script, use a package like youtube-transcript and pass it the video link or ID. For a deployed app, send the link to an API like Importly with fetch(), which returns the transcript from a server the same way it does locally.

Why does my YouTube transcript code work locally but fail on Vercel?

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.

Can I get a transcript for a video with no captions?

Yes. With "mode": "auto", Importly runs speech-to-text when there are no captions, in the same request, for $0.01 per minute.

Does it work with Shorts and youtu.be links?

Yes. watch?v=, youtu.be, /shorts/ and m.youtube.com links all work as pasted. See the YouTube Shorts transcript API post.

Related: Best YouTube transcript API, YouTube transcripts in Python, Download YouTube videos in Node.js, Video transcription API, Video to SRT subtitles API, YouTube transcription API.

Keep reading

Put video and audio links to work in your app

One API for files, transcripts and metadata. Free to try, no card required.

Try free →