Skip to content
EN
Get API key

YouTube Data / JavaScript

YouTube captions: choose a language and handle missing tracks

Choose automatic or uploader-provided YouTube captions by language, preserve timestamps, and handle missing tracks explicitly with JavaScript.

FlashData · Published

Two caption tracks with one selected below a video frame

A video can have English automatic captions, an uploader-provided Spanish track, both, or neither. Asking for a language does not create a track that the video does not have. This guide makes the caption choice explicit and shows how to save the selected track without silently substituting another language or caption source.

Automatic captions and uploader-provided captions

FlashData exposes two convenient sources: youtube_transcript defaults to automatic captions, while youtube_captions defaults to uploader-provided captions. Both support an explicit params.auto value: true selects automatic captions and false selects uploader-provided captions. Both retrieve existing YouTube captions and return timestamped segments.

Set params.language to the track you need, for example en, es or en-US. A regional code and a language-only code are not interchangeable promises. If the requested language and caption source are unavailable, the request can fail or have no usable text. The API does not automatically translate, generate speech-to-text, or fall back between track sources.

Choose one track before sending the request

Use Node.js 22 or later and an API key with available Credits. Set a video ID you are allowed to process. For the basic text export workflow, see Get YouTube subtitles with JavaScript.

bash
export FLASHDATA_API_KEY='your-api-key'
export YOUTUBE_VIDEO_ID='your-video-id'
export CAPTION_LANGUAGE='en'
export CAPTION_AUTO='true'

Use CAPTION_AUTO=false to ask for an uploader-provided track. The script sends exactly one request. It does not try every language or issue a second paid request automatically when the first one fails.

Fetch the chosen track and keep timestamps

Save the following code as caption-track.mjs. It validates the input choice, checks for tool-level errors as well as HTTP failures, and preserves the language and source information reported in the response.

javascript
import { writeFile } from "node:fs/promises";

const key = process.env.FLASHDATA_API_KEY;
const videoId = process.env.YOUTUBE_VIDEO_ID;
const language = process.env.CAPTION_LANGUAGE ?? "en";
const autoSetting = process.env.CAPTION_AUTO ?? "true";
if (!key || !/^[A-Za-z0-9_-]{11}$/.test(videoId ?? "")) {
  throw new Error("Set FLASHDATA_API_KEY and an 11-character YOUTUBE_VIDEO_ID.");
}
if (!["true", "false"].includes(autoSetting)) {
  throw new Error("CAPTION_AUTO must be true or false.");
}
if (!/^[A-Za-z0-9-]{1,35}$/.test(language)) {
  throw new Error("Use a caption language code such as en or en-US.");
}
const auto = autoSetting === "true";
const source = auto ? "youtube_transcript" : "youtube_captions";
const response = await fetch("https://data.flashdata.dev/v1/queries/realtime", {
  method: "POST",
  headers: { "Content-Type": "application/json", "X-API-Key": key },
  body: JSON.stringify({ source, video_id: videoId, params: { language, auto } }),
  signal: AbortSignal.timeout(60000),
});
const payload = await response.json();
if (!response.ok || payload.error || payload.status !== "done") {
  console.error(JSON.stringify({ httpStatus: response.status,
    requestId: response.headers.get("x-request-id"),
    detail: payload.detail ?? payload.message ?? payload.error }, null, 2));
  throw new Error("Caption request failed. Inspect the error before trying another track.");
}
const track = payload.results?.[0];
if (!Array.isArray(track?.segments) || !track.segments.some(s => s.text?.trim())) {
  throw new Error("No usable caption segments were returned for this selection.");
}
const saved = {
  requested: { videoId, language, auto },
  returned: { videoId: track.videoId, languageCode: track.languageCode,
    isAutoGenerated: track.isAutoGenerated, segments: track.segments },
};
await writeFile("caption-track.json", JSON.stringify(saved, null, 2));
await writeFile("caption-track.txt", track.fullText || track.segments.map(s => s.text).join("\n"));
console.log(`Saved ${track.segments.length} segments from ${track.languageCode}`);
bash
node caption-track.mjs

What to do when the requested track is missing

  • Check the error before changing caption settings. An invalid key, insufficient Credits or a timeout is not evidence that the video lacks captions.

  • If you already fetch video metadata, inspect hasTranscripts and transcriptLanguages as useful signals. A reported language does not guarantee that both automatic and uploader-provided tracks exist in that language.

  • If an alternative track is acceptable for your use case, choose it deliberately and make a separate request. Record the requested and returned language and isAutoGenerated value with the text.

  • If your workflow requires the exact track, mark the item unavailable and continue with other videos. Repeatedly sending the same request will not create missing captions.

Keep language and timestamp provenance with your text

Segments contain start, end and text; times are measured in seconds. Keep the video ID and language when splitting a transcript into search chunks. A timestamped video link can help a reader verify the original context. Avoid treating a caption segment as a new transcription that your application produced.

Automatic captions can contain recognition errors. If you use the text for summaries or quotations, provide a way to inspect the original segment and video. Availability and accuracy are separate questions: successfully retrieving a track does not guarantee that its wording is correct.

Compare the Transcript API and Captions API, or explore the YouTube Data APIs.