You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
Socket
Book a DemoInstallSign in
Socket

youtube-transcript-js-api

Package Overview
Dependencies
Maintainers
1
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

youtube-transcript-js-api

A JavaScript/TypeScript library to fetch YouTube video transcripts

1.0.0
Source
npmnpm
Version published
Weekly downloads
15
50%
Maintainers
1
Weekly downloads
 
Created
Source

YouTube Transcript JS API

A TypeScript/JavaScript library to fetch YouTube video transcripts. This is a complete port of the popular Python library youtube-transcript-api with additional features and TypeScript support.

Features

  • 🎯 Simple API: Easy-to-use methods for fetching transcripts
  • 🌍 Multi-language Support: Fetch transcripts in any available language
  • 🔄 Translation: Translate transcripts to different languages
  • 📄 Multiple Formats: Export transcripts in various formats (SRT, VTT, JSON, plain text)
  • 🛡️ Error Handling: Comprehensive error types for different scenarios
  • TypeScript: Full TypeScript support with type definitions
  • 🔄 Retry Logic: Built-in retry mechanism with exponential backoff
  • 🎭 Rate Limiting: Smart request handling to avoid YouTube's rate limits
  • 🖥️ CLI Support: Command-line interface for easy transcript fetching from the terminal

Table of Contents

Installation

npm install youtube-transcript-js-api

For CLI usage, install globally:

npm install -g youtube-transcript-js-api

Quick Start

import { getTranscript, YouTubeTranscriptApi } from 'youtube-transcript-js-api';

// Simple usage
const transcript = await getTranscript('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
console.log(transcript);

// Using the API class for more control
const api = new YouTubeTranscriptApi();
const transcript = await api.getTranscript('https://www.youtube.com/watch?v=dQw4w9WgXcQ');

CLI Usage:

# Get transcript from command line
youtube-transcript get "https://www.youtube.com/watch?v=dQw4w9WgXcQ"

# Save as SRT file
youtube-transcript get "VIDEO_URL" --format srt --output subtitles.srt

API Reference

Basic Usage

getTranscript(videoUrl, languages?)

Fetch transcript for a YouTube video.

import { getTranscript } from 'youtube-transcript-js-api';

// Get any available transcript
const transcript = await getTranscript('https://www.youtube.com/watch?v=dQw4w9WgXcQ');

// Get transcript in specific language
const transcript = await getTranscript(
  'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
  ['en']
);

// Try multiple languages in order of preference
const transcript = await getTranscript(
  'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
  ['en', 'es', 'fr']
);

listTranscripts(videoUrl)

List all available transcripts for a video.

import { listTranscripts } from 'youtube-transcript-js-api';

const transcriptList = await listTranscripts('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
console.log(transcriptList.transcripts);
// [
//   {
//     language: 'en',
//     languageName: 'English',
//     isGenerated: false,
//     isTranslatable: true,
//     url: '...'
//   },
//   ...
// ]

Advanced Usage

Using the API Class

import { YouTubeTranscriptApi } from 'youtube-transcript-js-api';

const api = new YouTubeTranscriptApi({
  userAgent: 'Custom User Agent',
  timeout: 15000,
  headers: {
    'Custom-Header': 'value'
  }
});

// Get transcript
const transcript = await api.getTranscript('VIDEO_URL');

// Get transcript in specific language
const transcript = await api.getTranscriptByLanguage('VIDEO_URL', 'es');

// Get translated transcript
const transcript = await api.getTranslatedTranscript('VIDEO_URL', 'fr', 'en');

// List available transcripts
const transcriptList = await api.listTranscripts('VIDEO_URL');

Formatting Transcripts

import {
  getTranscript,
  TextFormatter,
  SRTFormatter,
  VTTFormatter,
  JSONFormatter,
  TimestampFormatter
} from 'youtube-transcript-js-api';

const transcript = await getTranscript('VIDEO_URL');

// Plain text
const textFormatter = new TextFormatter();
const plainText = textFormatter.format(transcript);

// SRT format
const srtFormatter = new SRTFormatter();
const srtContent = srtFormatter.format(transcript);

// VTT format
const vttFormatter = new VTTFormatter();
const vttContent = vttFormatter.format(transcript);

// JSON format
const jsonFormatter = new JSONFormatter(true); // pretty print
const jsonContent = jsonFormatter.format(transcript);

// With timestamps
const timestampFormatter = new TimestampFormatter(true); // include end time
const timestampContent = timestampFormatter.format(transcript);

Error Handling

import {
  getTranscript,
  VideoUnavailableError,
  TranscriptsDisabledError,
  NoTranscriptFoundError,
  TranscriptRetrievalError,
  TooManyRequestsError
} from 'youtube-transcript-js-api';

try {
  const transcript = await getTranscript('VIDEO_URL');
} catch (error) {
  if (error instanceof VideoUnavailableError) {
    console.log('Video is private, deleted, or does not exist');
  } else if (error instanceof TranscriptsDisabledError) {
    console.log('Transcripts are disabled for this video');
  } else if (error instanceof NoTranscriptFoundError) {
    console.log('No transcript found in requested language');
    console.log('Available languages:', error.availableLanguages);
  } else if (error instanceof TooManyRequestsError) {
    console.log('Rate limited - wait before making more requests');
  } else if (error instanceof TranscriptRetrievalError) {
    console.log('Failed to retrieve transcript:', error.message);
  }
}

Supported Video URL Formats

The library supports various YouTube URL formats:

  • https://www.youtube.com/watch?v=VIDEO_ID
  • https://youtu.be/VIDEO_ID
  • https://www.youtube.com/embed/VIDEO_ID
  • https://www.youtube.com/v/VIDEO_ID
  • Direct video ID: VIDEO_ID

Supported Languages

The library supports all languages that YouTube supports for transcripts. Common language codes include:

  • en - English
  • tr - Turkish
  • es - Spanish
  • fr - French
  • de - German
  • it - Italian
  • pt - Portuguese
  • ru - Russian
  • ja - Japanese
  • ko - Korean
  • zh-Hans - Chinese (Simplified)
  • zh-Hant - Chinese (Traditional)

And many more...

CLI Usage

The library includes a command-line interface for easy transcript fetching from the terminal.

Installation for CLI

npm install -g youtube-transcript-js-api

CLI Commands

Get Transcript

# Get transcript in any available language
youtube-transcript get "https://www.youtube.com/watch?v=dQw4w9WgXcQ"

# Get transcript in specific language
youtube-transcript get "https://www.youtube.com/watch?v=dQw4w9WgXcQ" --language en

# Save transcript to file
youtube-transcript get "VIDEO_URL" --output transcript.txt

# Get transcript in SRT format
youtube-transcript get "VIDEO_URL" --format srt --output subtitles.srt

# Get transcript in VTT format
youtube-transcript get "VIDEO_URL" --format vtt --output subtitles.vtt

# Get transcript with timestamps
youtube-transcript get "VIDEO_URL" --format timestamp

# Get transcript in JSON format
youtube-transcript get "VIDEO_URL" --format json --output transcript.json

# Translate transcript to another language
youtube-transcript get "VIDEO_URL" --translate es --output transcript_spanish.txt

# Translate from specific source language
youtube-transcript get "VIDEO_URL" --language en --translate fr --output transcript_french.txt

List Available Transcripts

# List all available transcripts for a video
youtube-transcript list "https://www.youtube.com/watch?v=dQw4w9WgXcQ"

# Output example:
# Video ID: dQw4w9WgXcQ
# Available transcripts:
# 1. English (en) (auto-generated) [translatable]
# 2. Spanish (es) (manual) [translatable]
# 3. French (fr) (manual)

CLI Options

OptionShortDescriptionDefault
--language-lSpecific language code (e.g., en, es, fr)Any available
--format-fOutput format (text, srt, vtt, json, timestamp)text
--output-oOutput file (defaults to stdout)stdout
--translate-tTranslate to target languageNone

CLI Examples

# Basic usage - get any available transcript
youtube-transcript get "https://youtu.be/dQw4w9WgXcQ"

# Get English transcript and save as SRT
youtube-transcript get "dQw4w9WgXcQ" -l en -f srt -o subtitles.srt

# Translate English transcript to Spanish
youtube-transcript get "https://www.youtube.com/watch?v=dQw4w9WgXcQ" -l en -t es -o spanish.txt

# Get transcript with timestamps
youtube-transcript get "VIDEO_URL" -f timestamp

# List available languages
youtube-transcript list "VIDEO_URL"

# Pipe transcript to other tools
youtube-transcript get "VIDEO_URL" | grep "important keyword"

# Save JSON transcript for processing
youtube-transcript get "VIDEO_URL" -f json -o data.json

Configuration Options

interface TranscriptConfig {
  userAgent?: string;        // Custom user agent
  timeout?: number;          // Request timeout in milliseconds
  cookies?: string;          // Custom cookies
  headers?: Record<string, string>; // Custom headers
}

Rate Limiting

The library includes built-in protection against rate limiting:

  • Random delays between requests
  • Exponential backoff retry logic
  • Multiple user agents rotation
  • Request throttling

Examples

Save transcript as SRT file

import fs from 'fs';
import { getTranscript, SRTFormatter } from 'youtube-transcript-js-api';

const transcript = await getTranscript('VIDEO_URL');
const srtFormatter = new SRTFormatter();
const srtContent = srtFormatter.format(transcript);

fs.writeFileSync('transcript.srt', srtContent);

Get transcript with timestamps

import { getTranscript, TimestampFormatter } from 'youtube-transcript-js-api';

const transcript = await getTranscript('VIDEO_URL');
const formatter = new TimestampFormatter(true); // include end time
const formattedTranscript = formatter.format(transcript);

console.log(formattedTranscript);
// [0:00 - 0:03] Hello and welcome to this video
// [0:03 - 0:06] Today we're going to learn about...

Translate transcript

import { YouTubeTranscriptApi } from 'youtube-transcript-js-api';

const api = new YouTubeTranscriptApi();

// Translate English transcript to Spanish
const transcript = await api.getTranslatedTranscript('VIDEO_URL', 'es', 'en');

Error Types

  • YouTubeTranscriptError - Base error class
  • VideoUnavailableError - Video is private, deleted, or doesn't exist
  • TranscriptsDisabledError - Transcripts are disabled for the video
  • NoTranscriptFoundError - No transcript found in requested language
  • TranscriptRetrievalError - Failed to retrieve transcript data
  • TranslationError - Failed to translate transcript
  • TooManyRequestsError - Rate limited by YouTube

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT License - see the LICENSE file for details.

Disclaimer

This library is for educational and research purposes only. Please respect YouTube's Terms of Service and use this library responsibly.

Keywords

youtube

FAQs

Package last updated on 31 May 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts