# 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.

Canonical reference: https://flashdata.dev/blog/youtube-caption-language-selection
Blog: YouTube Data · JavaScript · FlashData
Published: 2026-09-26
RSS: https://flashdata.dev/blog/rss.xml

FlashData reads existing captions; it does not transcribe the audio. Read languageCode, requestedLanguageCode and captionSource to identify the returned track.

<a id="track-types"></a>

## Automatic captions and uploader-provided captions

youtube_transcript defaults to auto=true; youtube_captions defaults to auto=true. With auto=true, try these sources in the target language: native YouTube speech recognition, uploader captions, automatic captions of unknown type, then YouTube translations. With auto=false, only uploader captions are eligible.

Set `params.language` to the track you need, for example `en`, `es` or `en-US`. Omit language for English. Use a language code, "default" for the marked playback language, or "original" for the original audio language. Arrays accept 1–10 distinct selectors. Codes with or without -orig select any matching captions in that language, including named uploader tracks. Generic codes also match regional and script variants; explicit variants stay specific.

<a id="prepare"></a>

## Choose one track before sending the request

Use Node.js 22 or later and an [API key](https://flashdata.dev/app/api-keys) with available Credits. Set a video ID you are allowed to process. For the basic text export workflow, see [Get YouTube subtitles with JavaScript](https://flashdata.dev/blog/youtube-transcripts-javascript/reference.md).

```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.

<a id="script"></a>

## 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,
    requestedLanguageCode: track.requestedLanguageCode, captionSource: track.captionSource,
    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
```

<a id="missing"></a>

## 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.

<a id="timestamps"></a>

## 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](https://flashdata.dev/docs/sources/youtube_transcript/reference.md) and [Captions API](https://flashdata.dev/docs/sources/youtube_captions/reference.md), or explore the [YouTube Data APIs](https://flashdata.dev/products/youtube-data/reference.md).

## Related guides

- [All articles](https://flashdata.dev/blog/reference.md)
- [Guide to YouTube transcripts and captions](https://flashdata.dev/docs/guides/youtube-transcripts-and-captions/reference.md)
- [FlashData vs the official YouTube Data API](https://flashdata.dev/docs/guides/flashdata-vs-youtube-data-api/reference.md)
- [YouTube Data API](https://flashdata.dev/products/youtube-data/reference.md)
- [Compare plans and rates](https://flashdata.dev/pricing/youtube-data/reference.md)
- [Compare providers](https://flashdata.dev/compare/reference.md)
- [YouTube transcript APIs: existing captions or speech-to-text](https://flashdata.dev/blog/youtube-transcript-api-existing-captions/reference.md)
- [Get a YouTube channel’s recent videos with Python](https://flashdata.dev/blog/youtube-channel-videos-python/reference.md)
