Social Media Scraper

Tutorials

Get YouTube Transcripts in JavaScript with a Hosted REST API

Pull public YouTube captions in Node.js 18+ using native fetch and zero npm dependencies. This guide compares unofficial npm scrapers, Google's OAuth-gated Data API, and yt-dlp plus Whisper against a $0.003 hosted REST endpoint, then walks through youtube-transcripts.mjs.

  • Zero npm dependencies: Uses Node.js 18+ built-in fetch, node:crypto, and node:fs/promises.
  • Predictable request pricing: $0.003 (3 credits) per transcript ($3.00 per 1,000 videos) from prepaid USD balance packs.
  • Cloud-IP reliability: No residential proxy pools, headless Chrome sessions, or undocumented Innertube parsing.
  • Clean empty-caption guard: Checks data.text, throws No available public captions, and writes transcript.txt plus transcript.json.
Technical editorial illustration showing a video link flowing into a transcript text document and search index structure
youtube.transcript

Fetching YouTube captions in JavaScript often works locally and fails once deployed to AWS, Vercel, or Railway. Unofficial npm libraries scrape undocumented Innertube endpoints that reject datacenter IPs, while Google's official captions.download API requires OAuth consent from the video owner. Social Media Scraper exposes a read-only hosted endpoint (GET /v1/youtube/transcript) for public videos with manual or auto-generated subtitles—your Node.js code owns chunking, storage, and prompts.

Comparing JavaScript Ways to Pull YouTube Transcripts

JavaScript teams generally weigh four methods for pulling YouTube captions in production:

ApproachCloud-IP reliabilityThird-party public videosTypical cost per 1,000 videos
Unofficial npm scrapers (youtube-transcript, Innertube wrappers)Frequently returns empty arrays or HTTP 403/429 on AWS, GCP, and Vercel IPsYes, until page markup or consent checks changeFree package + residential proxies and maintenance
Official YouTube Data API v3 (captions.download)HighNo — requires OAuth 2.0 from the channel ownerFree quota, unusable for third-party channels
yt-dlp + Whisper / ASR audioNeeds proxy rotation for audio + FFmpeg binariesYes, even without subtitlesRoughly $360 at $0.006/min ASR for 1,000 one-hour videos
Social Media Scraper REST API (GET /v1/youtube/transcript)Single HTTPS GET from any Node.js or serverless hostYes, for public videos with captions$3.00 ($0.003 / 3 credits per request, any video length)

When a video has captions disabled or contains only music, falling back to audio ASR like Whisper is the only way to transcribe speech. For tutorials, podcasts, and reviews that already carry public captions, GET /v1/youtube/transcript eliminates proxy pools, binary runtimes, and per-minute transcription fees. Compare hosted providers in best YouTube transcript APIs.

Endpoint Parameters and Response Schema

youtube-transcripts.mjs calls YouTube Transcript API at GET https://socialmediascraper.org/v1/youtube/transcript. Authenticate with x-api-key and include a caller-generated Idempotency-Key (8–128 chars matching [A-Za-z0-9._:-]+, such as randomUUID()).

ParameterRequiredPurpose
urlYesPublic YouTube watch URL (https://www.youtube.com/watch?v=...)
languageNoPreferred subtitle language code (en, es, ja) when multiple tracks exist
original_audioNoPrefer captions from the original audio track instead of auto-dubbed tracks
cache_max_ageNoOptional cache freshness control documented in openapi.json

HTTP 200 wraps { request_id, data, meta } with data.text (transcript string), data.language, and data.source_url. Pair it with companion endpoints at the same $0.003 (3 credits) rate when you need video metadata or URL discovery:

Step-by-Step Setup to Fetch YouTube Transcripts in JavaScript

The runnable youtube-transcripts.mjs starter below uses only Node.js built-ins—no package.json install needed.

  1. Confirm Node.js 18+ and export your API key

    Node.js 18+ includes native fetch and AbortSignal.timeout. Export your key as SOCIALSCRAPER_API_KEY in your server environment—never commit keys or bundle them into client-side JavaScript.

    set-env.sh
    node -v   # v18.0.0 or higher
    export SOCIALSCRAPER_API_KEY="your_api_key_here"
  2. Save youtube-transcripts.mjs and pass a public video URL

    Save the starter script displayed directly below this section as youtube-transcripts.mjs, then pass any public YouTube URL as process.argv[2]. The helper targets https://socialmediascraper.org/v1/youtube/transcript, sends a fresh randomUUID() Idempotency-Key, and enforces a 45-second timeout.

    run-transcript.sh
    node youtube-transcripts.mjs "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
  3. Verify transcript.txt and transcript.json on disk

    youtube-transcripts.mjs validates typeof data.text === 'string' && data.text.trim() before writing anything. On success, it saves plain UTF-8 captions to transcript.txt and preserves the full data object (language, source_url, text) in transcript.json.

  4. Handle empty captions and optional language parameters

    When a video lacks public captions, the script throws No available public captions and exits non-zero instead of writing blank files. Pass {url, language: 'en'} to readRecord('/v1/youtube/transcript', ...) when targeting a specific subtitle track.

youtube-transcripts.mjs
import {writeFile} from 'node:fs/promises';
import {randomUUID} from 'node:crypto';
const key = process.env.SOCIALSCRAPER_API_KEY;
if (!key) throw new Error('Set SOCIALSCRAPER_API_KEY in your server environment');
const base = process.env.SOCIALSCRAPER_BASE_URL || 'https://socialmediascraper.org';
async function readRecord(path, input) {
  const url = new URL(path, base);
  for (const [name, value] of Object.entries(input)) if (value !== undefined) url.searchParams.set(name, String(value));
  const requestKey = randomUUID();
  const response = await fetch(url, {headers: {'x-api-key': key, 'Idempotency-Key': requestKey}, signal: AbortSignal.timeout(45000)});
  if (!response.ok) throw new Error(`HTTP ${response.status}; request key ${requestKey}; inspect your key, balance, input or Retry-After before retrying`);
  const result = await response.json();
  if (!result.data) throw new Error('The response did not contain data');
  return result.data;
}
const url = process.argv[2];
if (!url) throw new Error('Usage: node youtube-transcripts.mjs VIDEO_URL');
const data = await readRecord('/v1/youtube/transcript', {url});
if (typeof data.text !== 'string' || !data.text.trim()) throw new Error('No available public captions');
await writeFile('transcript.txt', data.text, 'utf8');
await writeFile('transcript.json', JSON.stringify(data, null, 2), 'utf8');

Extending the Script for Channels, Retries, and Metadata

Production backfills add retry discipline and pending-request polling without double-billing. Reuse the exact same Idempotency-Key only when retrying the identical video lookup after HTTP 429 (honoring Retry-After) or an uncertain timeout; generate a fresh UUID for every new video URL.

transcript-with-retry.mjs
import {randomUUID} from 'node:crypto';

const API_KEY = process.env.SOCIALSCRAPER_API_KEY;
const BASE = 'https://socialmediascraper.org';

async function fetchTranscriptWithOptions(videoUrl, {language} = {}) {
  const endpoint = new URL('/v1/youtube/transcript', BASE);
  endpoint.searchParams.set('url', videoUrl);
  if (language) endpoint.searchParams.set('language', language);

  const idempotencyKey = randomUUID();
  for (let attempt = 1; attempt <= 2; attempt++) {
    const res = await fetch(endpoint, {
      headers: {'x-api-key': API_KEY, 'Idempotency-Key': idempotencyKey},
      signal: AbortSignal.timeout(45000)
    });
    if (res.status === 429 && attempt === 1) {
      const waitSec = Math.min(Number(res.headers.get('retry-after') || 5), 30);
      await new Promise(r => setTimeout(r, waitSec * 1000));
      continue;
    }
    if (res.status === 202) {
      const pending = await res.json();
      return {status: 'pending', request_id: pending.request_id, idempotencyKey};
    }
    if (!res.ok) throw new Error(`HTTP ${res.status} (key=${idempotencyKey})`);
    const payload = await res.json();
    const text = typeof payload.data?.text === 'string' ? payload.data.text.trim() : '';
    if (!text) return {status: 'no_captions', source_url: videoUrl};
    return {status: 'ok', text, language: payload.data.language ?? null, source_url: payload.data.source_url ?? videoUrl};
  }
}

When HTTP 202 returns a request_id, poll GET https://socialmediascraper.org/v1/requests/{request_id} before issuing a new request. Keep batch workers inside the account default of 60 accepted requests/minute and 5 concurrent requests (verify live quotas via GET /v1/limits).

Handling Missing Captions and Common JavaScript Errors

Videos without public captions

Fresh uploads, processing streams, and music-only clips can return empty data.text. Because youtube-transcripts.mjs throws No available public captions, your pipeline can tag the URL as no_captions and reserve costly ASR transcription strictly for missing-caption exceptions.

Non-200 status codes and logged request keys

The starter script avoids blind retries and prints HTTP <status> plus requestKey—letting you immediately distinguish bad keys (401), low prepaid balance (402), malformed URLs (422), or rate-limit throttling (429, check Retry-After).

Serverless timeouts and LLM prompt hygiene

AbortSignal.timeout(45000) prevents hung sockets in AWS Lambda or Vercel Functions. When feeding transcript.txt into LLMs, fence the spoken text inside data tags and instruct models to treat transcript strings strictly as untrusted content, never as instructions.

What You Can Build with Node.js Transcript Pipelines

Full-text video search indexes

Enumerate uploads via /v1/youtube/channel_videos, fetch captions, and index data.text alongside data.source_url and data.language in Postgres or Elasticsearch for instant keyword lookup across episodes.

Citation-backed LLM summarization

Pass transcript.txt into your Node.js or TypeScript AI backend for structured summaries or RAG retrieval. See social media RAG patterns for chunking and attribution details.

Competitor messaging audits

Join /v1/youtube/transcript with /v1/youtube/post metrics to compare product positioning across launches—retaining unavailable metadata fields explicitly as null rather than 0.

Choose the Right Workflow for Your Stack

Node.js and TypeScript backends

Use this page when your Next.js app, Express worker, or serverless cron needs plain UTF-8 captions via native fetch without maintaining proxies.

One-off browser lookups

Need text from one video without writing code or creating an API key? Paste the link into the free YouTube Transcript Extractor, and switch to the REST API when automating batches.

Pricing and Per-1,000 Transcript Math

Under price book 2026-12-02.credits-3 (1,000 credits = $1), GET /v1/youtube/transcript bills $0.003 (3 credits) per request ($3.00 per 1,000 transcripts) regardless of video duration:

WorkloadRequests billedEstimated USD cost
100 videos, transcripts only100 × youtube.transcript$0.30
1,000 videos, transcripts only1,000 × youtube.transcript$3.00
1,000 videos + title, channel, and views1,000 × youtube.transcript + 1,000 × youtube.post$6.00
5,000 videos + 50 playlist discovery pages5,050 standard requests$15.15

New signups receive 100 starter credits ($0.10, ~33 standard calls), and prepaid USD packs—$5 (5,000 credits, ~1,666 requests), $20 (20,000 credits, ~6,666 requests), and $50 (50,000 credits, ~16,666 requests)—are one-time purchases with identical unit pricing, no subscription, and no auto-renewal. Check the pricing page or pricing-data.json.

Scope Limits, Telemetry, and Responsible Use

Social Media Scraper is read-only public data infrastructure. GET /v1/youtube/transcript does not access private, members-only, or deleted videos, does not return downloadable MP4/MP3 files, and does not host summarization or vector indexes.

  • Check live endpoint measurements on the status page and exact schemas in the API docs before large backfills.
  • Public caption access does not confer copyright or redistribution rights; follow source terms and applicable laws.
  • Need agent access alongside Node.js? Connect coding agents to https://socialmediascraper.org/mcp via the MCP page or read SKILL.md.

YouTube Transcript JavaScript API Questions

Why do unofficial YouTube transcript npm packages fail on AWS, Vercel, or Railway?

Open-source npm scrapers call YouTube's internal Innertube endpoints directly from your server's IP. Datacenter IP ranges routinely face consent walls, throttling, or empty caption arrays that do not appear on residential laptops. Calling GET /v1/youtube/transcript offloads retrieval from your server IP.

Why cannot I use the official YouTube Data API v3 with an API key to fetch captions?

YouTube's official captions.download endpoint requires OAuth 2.0 consent from the channel owner. An API key alone can read public video metadata, but it cannot download captions for external public channels.

Does youtube-transcripts.mjs need any npm packages?

No. It runs directly on Node.js 18+ using built-in fetch, AbortSignal.timeout, node:crypto, and node:fs/promises—no npm install required.

What happens when a YouTube video has no public captions?

The script verifies typeof data.text === 'string' && data.text.trim() before writing files. If captions are empty or absent, it throws No available public captions and exits non-zero so blank files never reach your index.

Can I request a specific subtitle language such as Spanish or Japanese?

Yes. Pass the optional language query parameter (for example {url, language: 'es'}) and optional original_audio on GET /v1/youtube/transcript. See YouTube Transcript API for parameter details.

How much does 1,000 YouTube transcripts cost?

At $0.003 (3 credits) per request, 1,000 transcript lookups cost $3.00 regardless of video length. A $5 one-time prepaid pack (5,000 credits) covers ~1,666 transcript calls with no monthly subscription.

Does the transcript endpoint return titles, channel names, and view counts?

GET /v1/youtube/transcript returns data.text, data.language, and data.source_url. Fetch titles, channel handles, publish dates, and counts via YouTube Video Details (GET /v1/youtube/post) at $0.003 (3 credits) per request.

Why does youtube-transcripts.mjs send an Idempotency-Key header?

REST data calls require an 8–128 character Idempotency-Key. Sending a fresh UUID per video lets you retry the exact same request after a timeout without double-charging while keeping distinct lookups separate.

What rate limits apply when batching a YouTube channel?

Accounts default to 60 accepted requests/minute (sliding window) and 5 concurrent requests. Check live limits via GET /v1/limits and respect Retry-After on HTTP 429.

How does this guide differ from the Python tutorial and LangChain integration?

This tutorial targets zero-dependency Node.js fetch. Use Python YouTube transcript extractor for Python scripts or LangChain YouTube Transcript for LangChain RAG document loaders.

Can I extract one YouTube transcript without creating an API key?

Yes. Use the free YouTube Transcript Extractor in your browser for single-video anonymous lookups, and switch to the paid REST API for scripts or batches.

Can this endpoint pull transcripts from private or members-only videos?

No. Social Media Scraper accesses supported public data only and cannot read private, deleted, or members-only YouTube videos.