Skip to content

YouTube Transcript API in JavaScript (Node.js)

This page shows how to get a YouTube transcript in JavaScript with TranscriptAPI. You send one HTTPS request with a video URL or ID and get back the transcript as JSON segments or plain text. The examples use Node.js and the built-in fetch, so there is nothing to install.

Prefer another language? See the Python and cURL quick starts.

  • An API key. Sign up to get 100 free credits (no card required), then copy a key from the API Keys dashboard.

  • Node.js 18 or newer, which includes fetch. Check with node --version.

  • Your key in an environment variable, so it never ends up in your code:

    Terminal window
    export TRANSCRIPT_API_KEY="your_api_key"

The examples use top-level await, so save them as .mjs files. Each successful transcript request costs 1 credit. Failed requests (4xx and 5xx) cost nothing. See Credit Usage & Billing.

Save this as transcript.mjs and run node transcript.mjs:

const API_KEY = process.env.TRANSCRIPT_API_KEY;
const params = new URLSearchParams({
video_url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
});
const response = await fetch(
`https://transcriptapi.com/api/v2/youtube/transcript?${params}`,
{ headers: { Authorization: `Bearer ${API_KEY}` } },
);
if (!response.ok) {
throw new Error(`${response.status}: ${JSON.stringify(await response.json())}`);
}
const data = await response.json();
console.log(data.video_id, data.language, data.lengthText);
for (const segment of data.transcript.slice(0, 3)) {
console.log(`[${segment.start}s] ${segment.text}`);
}

video_url accepts a full URL (https://www.youtube.com/watch?v=...), a short URL (https://youtu.be/...), or the 11-character video ID.

Response (shortened):

{
"video_id": "dQw4w9WgXcQ",
"language": "en",
"transcript": [
{ "text": "[♪♪♪]", "start": 1.36, "duration": 1.68 },
{ "text": "♪ We're no strangers to love ♪", "start": 18.64, "duration": 3.24 },
{ "text": "♪ You know the rules\nand so do I ♪", "start": 22.64, "duration": 4.32 }
],
"length_seconds": 213,
"lengthText": "3:33"
}

Each segment has the caption text, its start time in seconds, and its duration in seconds. The full field list is in the API Reference.

Not every video has a transcript. Before you spend a credit, ask GET /youtube/info. It takes the same video_url as the transcript endpoint. The API Reference says “no credit is consumed” and “The same API key and active plan are required as for the transcript endpoint.”

A 200 gives you the video’s metadata (title, author_name, author_url, thumbnail_url) and available_languages, a list of code, name, and kind entries. A 404 means the video does not exist or has no captions, so there is nothing to fetch.

const API_KEY = process.env.TRANSCRIPT_API_KEY;
const BASE_URL = "https://transcriptapi.com/api/v2";
const headers = { Authorization: `Bearer ${API_KEY}` };
const params = new URLSearchParams({ video_url: "dQw4w9WgXcQ" });
// No credits: does the video exist, and does it have captions?
const info = await fetch(`${BASE_URL}/youtube/info?${params}`, { headers });
if (info.status === 404) {
console.log("No transcript for this video:", (await info.json()).detail);
} else if (!info.ok) {
throw new Error(`${info.status}: ${JSON.stringify(await info.json())}`);
} else {
const { metadata, available_languages } = await info.json();
console.log(metadata.title, "by", metadata.author_name);
console.log("Languages:", available_languages.map((lang) => lang.code));
// 1 credit: now fetch the transcript
const response = await fetch(`${BASE_URL}/youtube/transcript?${params}`, { headers });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
console.log(data.transcript.length, "segments");
}

This check is most useful in batch jobs, where some videos in a list have no captions.

Set format to text and include_timestamp to false to get the whole transcript as one string. That’s useful for LLM prompts, search indexes, or notes. Add send_metadata to get the video title and channel as well.

import { writeFile } from "node:fs/promises";
const API_KEY = process.env.TRANSCRIPT_API_KEY;
const params = new URLSearchParams({
video_url: "dQw4w9WgXcQ",
format: "text",
include_timestamp: "false",
send_metadata: "true",
});
const response = await fetch(
`https://transcriptapi.com/api/v2/youtube/transcript?${params}`,
{ headers: { Authorization: `Bearer ${API_KEY}` } },
);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
await writeFile(`${data.video_id}.txt`, data.transcript, "utf8");
console.log("Saved transcript of:", data.metadata.title);

With include_timestamp left at true, text output keeps one line per segment in the form [18.64s] text.

/youtube/info costs no credits and lists the languages a video offers. Pass a comma-separated priority list in language and the API returns the first one that exists. The language field in the response tells you which one you got. Codes starting with asr are YouTube’s auto-generated captions.

const API_KEY = process.env.TRANSCRIPT_API_KEY;
const BASE_URL = "https://transcriptapi.com/api/v2";
const headers = { Authorization: `Bearer ${API_KEY}` };
// No credits: list the transcript languages a video offers
const info = await fetch(
`${BASE_URL}/youtube/info?${new URLSearchParams({ video_url: "dQw4w9WgXcQ" })}`,
{ headers },
).then((r) => r.json());
console.log(info.available_languages.map((lang) => lang.code));
// 1 credit: German if available, otherwise English
const data = await fetch(
`${BASE_URL}/youtube/transcript?${new URLSearchParams({ video_url: "dQw4w9WgXcQ", language: "de,en" })}`,
{ headers },
).then((r) => r.json());
console.log("Got:", data.language);

If none of the requested languages exist, the API returns a 404 that lists the languages the video does have. See language for the full rules.

Failed requests cost no credits. Every error response has a detail field. These are the ones you are most likely to meet.

401 Unauthorized. The API key is missing or wrong. The response has a WWW-Authenticate: Bearer header and a short message:

{ "detail": "Invalid API key" }

Check that TRANSCRIPT_API_KEY is set in the environment that runs Node.js, and that the key still exists in the API Keys dashboard. Don’t retry until you fix the key.

402 Payment Required. You have run out of credits, or you have no active plan. Here detail is an object with a reason and a link to fix it:

{
"detail": {
"message": "You have an active plan, but you've run out of credits.",
"reason": "insufficient_credits",
"action_label": "Top up credits",
"action_url": "https://transcriptapi.com/top-up"
}
}

When reason is no_active_paid_plan, action_url points to Billing instead. Free endpoints such as /youtube/info also need an active plan, so they can return 402 too. Open action_url, then send the request again.

404 Not Found. There is no transcript to return. The code field tells you why:

{
"detail": "No transcript available for video tfLTHCpPsSY",
"code": "no_captions"
}

Other codes are video_unavailable, age_restricted, live_not_started, and no_transcript_for_requested_languages. The last one comes with an available_languages list you can retry with. Branch on code, not on detail. Don’t retry the same request, except live_not_started after the stream has aired. Each code is explained in 404 error codes.

429 Too Many Requests. You went over your plan’s rate limit, which all API keys on your account share. Wait the number of seconds in the Retry-After header, then retry. Rate-limited requests cost no credits.

You might also see 422 when video_url is not a valid URL or video ID (fix the input), or 408 and 503 for a temporary failure (retry after a few seconds).

Retry 408, 429, and 503, and wait for the Retry-After header when the API sends one. Don’t retry the other errors, because the request itself needs fixing.

const API_KEY = process.env.TRANSCRIPT_API_KEY;
const RETRYABLE = new Set([408, 429, 503]);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function getTranscript(videoUrl, options = {}, maxRetries = 3) {
const params = new URLSearchParams({ video_url: videoUrl, ...options });
for (let attempt = 0; attempt < maxRetries; attempt++) {
const response = await fetch(
`https://transcriptapi.com/api/v2/youtube/transcript?${params}`,
{ headers: { Authorization: `Bearer ${API_KEY}` } },
);
if (response.ok) return response.json();
if (RETRYABLE.has(response.status) && attempt < maxRetries - 1) {
// Use Retry-After when the API sends it, otherwise back off 1s, 2s, 4s...
const retryAfter = Number(response.headers.get("Retry-After")) || 2 ** attempt;
await sleep(retryAfter * 1000);
continue;
}
// 401 bad key, 402 no credits, 404 no transcript, 422 invalid URL: don't retry
const body = await response.json();
throw new Error(`${response.status}: ${JSON.stringify(body.detail)}`);
}
}
console.log((await getTranscript("dQw4w9WgXcQ")).lengthText);

The full error list and response bodies are in Error Handling.

Get transcripts for a channel’s latest videos

Section titled “Get transcripts for a channel’s latest videos”

/youtube/channel/latest costs no credits and returns a channel’s 15 most recent uploads. It accepts an @handle, a channel URL, or a UC... ID. Each transcript you then fetch costs 1 credit.

const API_KEY = process.env.TRANSCRIPT_API_KEY;
const BASE_URL = "https://transcriptapi.com/api/v2";
const headers = { Authorization: `Bearer ${API_KEY}` };
// No credits: the channel's 15 most recent uploads (RSS)
const latest = await fetch(
`${BASE_URL}/youtube/channel/latest?${new URLSearchParams({ channel: "@TED" })}`,
{ headers },
).then((r) => r.json());
// 1 credit per transcript
for (const video of latest.results.slice(0, 3)) {
const params = new URLSearchParams({
video_url: video.videoId,
format: "text",
include_timestamp: "false",
});
const response = await fetch(`${BASE_URL}/youtube/transcript?${params}`, { headers });
if (response.ok) {
const { transcript } = await response.json();
console.log(video.title, "->", transcript.split(/\s+/).length, "words");
} else {
console.log(video.title, "-> no transcript", response.status);
}
}

The same key also works for search, paginated channel videos, and playlists.