### Install youtube-transcript-api Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/README.md Install the library using npm. This command is used to add the package to your project's dependencies. ```bash npm install youtube-transcript-api ``` -------------------------------- ### Transcript Entry Example Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/types.md An example of a single transcript entry, including the text content and its start time and duration within the video. ```javascript { language: "English (auto-generated)", transcript: [ { text: "we're no strangers to", start: "18.8", dur: "7.239" }, { text: "love you know the rules and so do", start: "21.8", dur: "7.84" } ] } ``` -------------------------------- ### Custom Timeout and User-Agent Configuration Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/configuration.md Example of initializing the client with a custom timeout and a specific User-Agent header. This configuration is applied globally to all requests made by this client instance. ```javascript import TranscriptClient from 'youtube-transcript-api'; const client = new TranscriptClient({ timeout: 15000, headers: { "User-Agent": "Custom-Agent/1.0" } }); await client.ready; const transcript = await client.getTranscript("dQw4w9WgXcQ"); ``` -------------------------------- ### PlayabilityStatus Example Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/types.md Represents the playability status of a video. Use this to check if a video is playable and understand any restrictions. ```javascript { status: "OK", playableInEmbed: true, miniplayer: { miniplayerRenderer: { playbackMode: "PLAYBACK_MODE_ALLOW" } }, contextParams: "Q0FFU0FnZ0I=" } ``` -------------------------------- ### Handle Mixed Results with Bulk Transcripts Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/api-reference/TranscriptClient.md This example demonstrates how to process results from `bulkGetTranscript` when some videos may not have transcripts available. It checks the `tracks` array to determine availability. ```javascript import TranscriptClient from "youtube-transcript-api"; const client = new TranscriptClient(); await client.ready; // One video with transcript, one without const results = await client.bulkGetTranscript([ "dQw4w9WgXcQ", // Has transcript "JGJPVl7iQUM" // No transcript available ]); results.forEach(result => { if (result.tracks.length === 0) { console.log(`${result.title}: No transcript available`); } else { console.log(`${result.title}: ${result.tracks.length} transcript(s)`); } }); ``` -------------------------------- ### PlayabilityStatus Example: Video Not Found Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/types.md Illustrates the playability status when a video is not found or unavailable. The 'reason' field provides a human-readable explanation. ```javascript { status: "LOGIN_REQUIRED", reason: "Video not found or unavailable" } ``` -------------------------------- ### Thumbnail Example Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/types.md Represents a single video thumbnail image. Includes the URL and dimensions. This is used within the 'thumbnails' array in the MicroformatObject. ```javascript { url: "https://i.ytimg.com/vi/dQw4w9WgXcQ/maxresdefault.jpg", width: 1280, height: 720 } ``` -------------------------------- ### TranscriptClient Constructor Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/SOURCE_ANALYSIS.md Initializes the Axios instance with default headers and base URL, and starts asynchronous fetching of Firebase credentials. Accepts optional Axios configuration. ```javascript constructor(AxiosOptions) { this.#instance = axios.create({ ...(AxiosOptions || {}), headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:139.0) Gecko/20100101 Firefox/139.0", ...(AxiosOptions?.headers || {}) }, baseURL: "https://www.youtube-transcript.io/" }); this.ready = new Promise(async resolve => { this.#firebase_cfg_creds = await this.#get_firebase_cfg_creds(); resolve(); }); } ``` -------------------------------- ### Language Object Example Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/types.md An example of a language object, specifying the human-readable label and the ISO 639-1 language code. ```javascript { label: "English (auto-generated)", languageCode: "en" } ``` -------------------------------- ### client.ready Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/README.md A promise that resolves when the client is fully initialized and ready to use. It's crucial to await this promise before making any transcript requests to ensure the client has completed its necessary setup, including scraping Firebase configuration credentials. ```APIDOC ## `client.ready : Promise` A promise that resolves when the client is fully initialized and ready to use. Upon instantiation of `TranscriptClient`, Firebase configuration credentials for the youtube-transcript.io application need to be scraped. Always `await` this before calling methods. ``` -------------------------------- ### Request Options Merge Behavior Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/configuration.md Illustrates how request-level options merge with constructor-level options, with request-level settings taking precedence. This example shows a request using a shorter timeout than the client's default. ```javascript // Constructor-level timeout: 10 seconds const client = new TranscriptClient({ timeout: 10000 }); // This request uses 5 second timeout (overrides constructor default) const transcript = await client.getTranscript(id, { timeout: 5000 }); // This request uses 10 second timeout (from constructor) const transcript2 = await client.getTranscript(id2); ``` -------------------------------- ### General Error Handling Pattern Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/errors.md A common pattern for handling errors when fetching YouTube transcripts. This example demonstrates how to use a try-catch block to manage potential errors and log their messages and stack traces. ```javascript import TranscriptClient from "youtube-transcript-api"; const client = new TranscriptClient(); await client.ready; try { const transcript = await client.getTranscript("videoId"); } catch (error) { if (error instanceof Error) { console.error("Error message:", error.message); console.error("Stack trace:", error.stack); } // Handle based on error message } ``` -------------------------------- ### Basic Usage: Get Transcript for a Single Video Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/README.md Demonstrates how to initialize the client, wait for it to be ready, and retrieve the transcript for a specific YouTube video. Accesses the video title and the transcript text of the first track. ```javascript import TranscriptClient from "youtube-transcript-api"; const client = new TranscriptClient(); await client.ready; // Wait for initialization const transcript = await client.getTranscript("dQw4w9WgXcQ"); console.log(transcript.title); console.log(transcript.tracks[0].transcript); ``` -------------------------------- ### Video Without Transcript Response Example Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/README.md This JSON object illustrates a response for a YouTube video where no transcript is available. The 'tracks' array is empty, and 'playabilityStatus' may indicate that a transcript is not available. ```json { "id": "JGJPVl7iQUM", "title": "Clair de Lune (Studio Version)", "tracks": [], "languages": [ { "label": "en", "languageCode": "en" } ], "isLive": false, "isLoginRequired": false, "playabilityStatus": { "status": "OK", "reason": "Transcript not available" } } ``` -------------------------------- ### Handle Network Errors with Axios Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/errors.md Implement robust error handling for network-related issues using `axios.isAxiosError`. This example shows how to catch and differentiate common Axios error codes and HTTP statuses. ```javascript import TranscriptClient from "youtube-transcript-api"; import axios from "axios"; const client = new TranscriptClient({ timeout: 10000 // 10 second timeout }); await client.ready; try { const transcript = await client.getTranscript("dQw4w9WgXcQ"); } catch (error) { if (axios.isAxiosError(error)) { if (error.code === "ECONNREFUSED") { console.error("Could not connect to youtube-transcript.io"); } else if (error.code === "ENOTFOUND") { console.error("DNS resolution failed"); } else if (error.code === "ECONNABORTED") { console.error("Request timeout"); } else if (error.response?.status === 429) { console.error("Rate limited - try again later"); } else if (error.response?.status >= 500) { console.error("Server error on youtube-transcript.io"); } else { console.error("Network error:", error.message); } } else { console.error("Unknown error:", error); } } ``` -------------------------------- ### Transcript Data Structure Example Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/README.md This JSON structure represents the data returned for a single video transcript. It includes metadata such as video title, description, language, and playability status. Note that the 'Transcript not available' status is indicated. ```json [ { "id": "JGJPVl7iQUM", "microformat": { "playerMicroformatRenderer": { "category": "Music", "description": { "simpleText": "Provided to YouTube by IIP-DDS\n\nClair de Lune (Studio Version) \u00b7 Johann Debussy\n\nClair de Lune (Studio Version)\n\n\u2117 Michael Lee Moen\n\nReleased on: 2021-12-14\n\nProducer: Michael Lee Moen\nMusic Publisher: Claude Debussy\nComposer: Claude Debussy\n\nAuto-generated by YouTube." }, "externalChannelId": "UC2VEp_GJTawei2IkYuqQdFA", "lengthSeconds": "311", "ownerChannelName": "Johann Debussy", "publishDate": "2021-12-14", "title": { "simpleText": "Clair de Lune (Studio Version)" } } }, "isLive": false, "isLoginRequired": false, "languages": [ { "label": "en", "languageCode": "en" } ], "playabilityStatus": { "status": "OK", "reason": "Transcript not available" }, "title": "Clair de Lune (Studio Version)", "tracks": [] }, ... ] ``` -------------------------------- ### Video Not Found or Unavailable Response Example Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/README.md This JSON object represents a scenario where the requested YouTube video is not found or is unavailable. Key fields like 'id' and 'title' are empty, and 'playabilityStatus' indicates an error, such as 'LOGIN_REQUIRED' or 'PLAYABILITY_STATUS_NOK'. ```json { "id": "", "title": "", "tracks": [], "isLive": false, "languages": [], "isLoginRequired": false, "playabilityStatus": { "status": "LOGIN_REQUIRED", "reason": "Video not found or unavailable" }, "failedReason": "PLAYABILITY_STATUS_NOK" } ``` -------------------------------- ### Get Transcript for Unavailable Video Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/README.md Example of calling getTranscript when the transcript is not available for a given video ID. This demonstrates the expected JSON response structure in such cases. ```javascript await client.getTranscript("JGJPVl7iQUM"); ``` ```json { "id": "JGJPVl7iQUM", "microformat": { "playerMicroformatRenderer": { "category": "Music", "description": { "simpleText": "Provided to YouTube by IIP-DDS\n\nClair de Lune (Studio Version) · Johann Debussy\n\nClair de Lune (Studio Version)\n\n℗ Michael Lee Moen\n\nReleased on: 2021-12-14\n\nProducer: Michael Lee Moen\nMusic Publisher: Claude Debussy\nComposer: Claude Debussy\n\nAuto-generated by YouTube." }, "externalChannelId": "UC2VEp_GJTawei2IkYuqQdFA", "lengthSeconds": "311", "ownerChannelName": "Johann Debussy", "publishDate": "2021-12-14", "title": { "simpleText": "Clair de Lune (Studio Version)" } } }, "isLive": false, "isLoginRequired": false, "languages": [ { "label": "en", "languageCode": "en" } ], "playabilityStatus": { "status": "OK", "reason": "Transcript not available" }, "title": "Clair de Lune (Studio Version)", "tracks": [] } ``` -------------------------------- ### Get Transcript for Non-existent Video Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/README.md Example of calling getTranscript for a video ID that does not exist or is unavailable. This shows the API response indicating login is required or the video is not found. ```javascript await client.getTranscript("1dsfsdfsdfs"); ``` ```json { "id": "", "title": "", "tracks": [], "isLive": false, "languages": [], "isLoginRequired": false, "playabilityStatus": { "status": "LOGIN_REQUIRED", "reason": "Video not found or unavailable" }, "failedReason": "PLAYABILITY_STATUS_NOK" } ``` -------------------------------- ### Configure TranscriptClient with Environment Variables Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/configuration.md Instantiate the TranscriptClient, passing environment variables for timeout and proxy configuration. Ensure environment variables are parsed correctly for numerical values. ```javascript const client = new TranscriptClient({ timeout: parseInt(process.env.TRANSCRIPT_API_TIMEOUT || '10000'), proxy: process.env.HTTP_PROXY ? { host: new URL(process.env.HTTP_PROXY).hostname, port: parseInt(new URL(process.env.HTTP_PROXY).port) } : undefined }); ``` -------------------------------- ### Successful Transcript Response Example Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/README.md This JSON object represents a successful response when a transcript is available for a YouTube video. It includes video metadata and the transcript data itself, broken down by text segments with start times and durations. ```json { "id": "dQw4w9WgXcQ", "title": "Rick Astley - Never Gonna Give You Up", "tracks": [ { "language": "English (auto-generated)", "transcript": [ { "text": "we're no strangers to love", "start": "18.8", "dur": "7.239" } ] } ], "languages": [ { "label": "English (auto-generated)", "languageCode": "en" } ], "isLive": false, "isLoginRequired": false, "author": "Rick Astley", "channelId": "UCuAXFkgsw1L7xaCfnd5JJOw", "keywords": ["rick astley", "never gonna give you up"], "microformat": { "playerMicroformatRenderer": { "title": { "simpleText": "Rick Astley - Never Gonna Give You Up" }, "lengthSeconds": "213", "category": "Music", "viewCount": "1646819896", "thumbnail": { "thumbnails": [ { "url": "https://i.ytimg.com/vi/dQw4w9WgXcQ/maxresdefault.jpg", "width": 1280, "height": 720 } ] } } }, "playabilityStatus": { "status": "OK" } } ``` -------------------------------- ### Project File Structure Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/00_START_HERE.md Illustrates the directory structure of the youtube-transcript-api project, highlighting the purpose of each markdown file. ```bash output/ ├── 00_START_HERE.md ← You are here ├── README.md ← Overview & quick start ├── api-reference/ │ └── TranscriptClient.md ← Complete API reference ├── types.md ← Data types & structures ├── configuration.md ← Configuration options ├── errors.md ← Error handling guide ├── USAGE_PATTERNS.md ← 17 practical patterns ├── SOURCE_ANALYSIS.md ← Code analysis └── INDEX.md ← Master index & navigation ``` -------------------------------- ### Async Initialization Pattern Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/SOURCE_ANALYSIS.md The client uses a Promise-based lazy initialization pattern. Users must await `ready` before using the client. ```javascript this.ready = new Promise(async resolve => { // Async initialization work resolve(); }); ``` -------------------------------- ### Correctly Await Client Initialization Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/errors.md Always await `client.ready` before calling transcript retrieval methods to ensure the client is fully initialized. This prevents the 'client not fully initialized!' error. ```javascript import TranscriptClient from "youtube-transcript-api"; const client = new TranscriptClient(); // ✓ CORRECT: Await client.ready await client.ready; const transcript = await client.getTranscript("dQw4w9WgXcQ"); ``` -------------------------------- ### Transcript Entry Structure Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/types.md Defines the structure of a single transcript entry, including the text, start time, and duration. ```typescript { text: string; start: string; dur: string; } ``` -------------------------------- ### ESM Entry Point Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/SOURCE_ANALYSIS.md Direct ES Module import for the library. Uses Axios/Cheerio ESM versions. ```javascript import TranscriptClient from "youtube-transcript-api"; ``` -------------------------------- ### TranscriptClient Constructor Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/api-reference/TranscriptClient.md Initializes a new TranscriptClient instance. It sets up an internal Axios client and begins fetching necessary Firebase credentials. The client is not ready until the `ready` property is awaited. ```APIDOC ## new TranscriptClient([AxiosOptions]) ### Description Creates a new `TranscriptClient` instance. The constructor initializes an internal Axios HTTP client and automatically begins fetching Firebase configuration credentials required for API authentication. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature `constructor(AxiosOptions?: AxiosRequestConfig)` ### Parameters | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | AxiosOptions | AxiosRequestConfig | No | `{}` | Custom Axios configuration object passed to the internal Axios instance. Useful for setting custom headers, timeouts, proxies, auth, or other Axios request options. See [Axios request config documentation](https://axios-http.com/docs/req_config) | ### Example ```javascript import TranscriptClient from "youtube-transcript-api"; // Basic initialization const client = new TranscriptClient(); // With custom Axios options const client = new TranscriptClient({ timeout: 10000, headers: { "User-Agent": "Mozilla/5.0 (Custom User Agent)" } }); ``` ``` -------------------------------- ### Get Video Transcript Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/README.md Fetches the transcript for a given YouTube video ID. Requires the 'youtube-transcript-api' package. The output is logged to the console. ```javascript const transcript = await client.getTranscript("dQw4w9WgXcQ"); console.log(transcript); ``` -------------------------------- ### Format Transcript with Timestamps Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/USAGE_PATTERNS.md Transforms transcript data into an array of objects, each containing start time, duration, and text. Useful for displaying transcripts with precise timing. ```javascript export function transcriptWithTimestamps(transcript) { if (!transcript.tracks || transcript.tracks.length === 0) { return []; } const track = transcript.tracks[0]; return track.transcript.map(entry => ({ time: parseFloat(entry.start), duration: parseFloat(entry.dur), text: entry.text })); } // Usage const withTimestamps = transcriptWithTimestamps(transcript); withTimestamps.forEach(({ time, duration, text }) => { console.log(`${time.toFixed(1)}s [${duration.toFixed(1)}s] ${text}`); }); ``` -------------------------------- ### Project File Structure Overview Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/INDEX.md Overview of the directory structure for the YouTube Transcript API project, highlighting key files and their purposes. ```text output/ ├── INDEX.md ← You are here ├── README.md ← Start here ├── USAGE_PATTERNS.md ← Real-world examples (856 lines) ├── configuration.md ← Config options (547 lines) ├── errors.md ← Error reference (439 lines) ├── types.md ← Data types (372 lines) └── api-reference/ └── TranscriptClient.md ← API reference (299 lines) ``` -------------------------------- ### Initialize TranscriptClient Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/api-reference/TranscriptClient.md Instantiate the TranscriptClient. You can provide custom Axios request configurations for options like timeouts or headers. ```javascript import TranscriptClient from "youtube-transcript-api"; // Basic initialization const client = new TranscriptClient(); // With custom Axios options const client = new TranscriptClient({ timeout: 10000, headers: { "User-Agent": "Mozilla/5.0 (Custom User Agent)" } }); ``` -------------------------------- ### Basic Transcript Fetch Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/00_START_HERE.md Instantiate the client, wait for it to be ready, and fetch a transcript for a given video ID. Logs the video title and the first entry of the first track. ```javascript import TranscriptClient from "youtube-transcript-api"; const client = new TranscriptClient(); await client.ready; const transcript = await client.getTranscript("dQw4w9WgXcQ"); console.log(transcript.title); console.log(transcript.tracks[0].transcript[0]); ``` -------------------------------- ### Initialize TranscriptClient with AxiosOptions Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/configuration.md The TranscriptClient constructor accepts an optional AxiosOptions parameter to customize the internal HTTP client. This is the primary way to configure the library's network behavior. ```javascript const client = new TranscriptClient(AxiosOptions); ``` -------------------------------- ### Get Transcript Data Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/api-reference/TranscriptClient.md Fetches the transcript and metadata for a single YouTube video. Ensure the client is ready by awaiting `client.ready` before calling this method. The video ID is a required parameter. ```javascript import TranscriptClient from "youtube-transcript-api"; const client = new TranscriptClient(); await client.ready; const transcript = await client.getTranscript("dQw4w9WgXcQ"); console.log("Video title:", transcript.title); console.log("Languages available:", transcript.languages.map(l => l.label)); if (transcript.tracks.length > 0) { const english = transcript.tracks[0]; console.log("First 5 transcript entries:"); english.transcript.slice(0, 5).forEach(entry => { console.log(`[${entry.start}s] ${entry.text}`); }); } else { console.log("No transcripts available for this video"); } ``` -------------------------------- ### Mock Client for Unit Testing Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/USAGE_PATTERNS.md Create a mock client class to simulate the behavior of the TranscriptClient for unit testing. This allows testing components that depend on the API without making actual network requests. ```javascript export class MockTranscriptClient { constructor(transcriptData = {}) { this.ready = Promise.resolve(); this.transcriptData = transcriptData; } async getTranscript(id) { if (!(id in this.transcriptData)) { throw new Error("invalid video ID"); } return this.transcriptData[id]; } async bulkGetTranscript(ids) { const results = []; const missing = []; for (const id of ids) { if (id in this.transcriptData) { results.push(this.transcriptData[id]); } else { missing.push(id); } } if (missing.length > 0) { throw new Error("video not found or unavailable"); } return results; } } // Usage in tests const mockClient = new MockTranscriptClient({ "vid1": { id: "vid1", title: "Test Video", tracks: [] }, "vid2": { id: "vid2", title: "Test Video 2", tracks: [] } }); const transcript = await mockClient.getTranscript("vid1"); ``` -------------------------------- ### Client Factory with Custom Configuration Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/USAGE_PATTERNS.md Create clients with different configurations for different use cases, such as fast failure, robustness, or anonymous access. Each factory function returns a new TranscriptClient instance with specific settings. ```javascript import TranscriptClient from "youtube-transcript-api"; export function createFastClient() { return new TranscriptClient({ timeout: 5000, // Fast failure maxRedirects: 2 }); } export function createRobustClient() { return new TranscriptClient({ timeout: 30000, // More tolerant maxRedirects: 10 }); } export function createAnonClient() { return new TranscriptClient({ headers: { "User-Agent": "Mozilla/5.0 (generic)" } }); } ``` -------------------------------- ### Initialize Client with Timeout Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/errors.md This function initializes the TranscriptClient and uses `Promise.race` to enforce a timeout, preventing indefinite waiting if the client fails to initialize. ```javascript async function initializeClient(axiosOptions) { const client = new TranscriptClient(axiosOptions); try { // Wait for initialization with timeout await Promise.race([ client.ready, new Promise((_, reject) => setTimeout(() => reject(new Error("Client initialization timeout")), 30000) ) ]); return client; } catch (error) { console.error("Failed to initialize client:", error); throw error; } } ``` -------------------------------- ### Default Client Configuration Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/configuration.md Shows the default configuration applied by the library, including baseURL and User-Agent headers. User-provided options are deep-merged with these defaults. ```javascript { baseURL: "https://www.youtube-transcript.io/", headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:139.0) Gecko/20100101 Firefox/139.0" }, // All other options: Axios defaults } ``` -------------------------------- ### CommonJS Import Style Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/README.md Demonstrates how to import the TranscriptClient using CommonJS module syntax. ```javascript const TranscriptClient = require("youtube-transcript-api"); ``` -------------------------------- ### Corporate Proxy Configuration Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/configuration.md Demonstrates how to configure the client to use a corporate proxy for network requests. This includes setting the proxy protocol, host, port, and authentication details. ```javascript import TranscriptClient from 'youtube-transcript-api'; const client = new TranscriptClient({ proxy: { protocol: 'http', host: 'corporate-proxy.company.com', port: 3128, auth: { username: 'employee', password: 'proxy-password' } }, timeout: 20000 }); await client.ready; const transcript = await client.getTranscript("dQw4w9WgXcQ"); ``` -------------------------------- ### Incorrectly Call Methods Before Client Ready Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/errors.md Calling transcript methods without awaiting `client.ready` will result in the 'client not fully initialized!' error. Ensure proper async/await usage. ```javascript import TranscriptClient from "youtube-transcript-api"; const client = new TranscriptClient(); // ✗ WRONG: Do not call methods without awaiting client.ready const transcript = await client.getTranscript("dQw4w9WgXcQ"); // Error: "client not fully initialized!" ``` -------------------------------- ### Basic Usage of TranscriptClient Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/README.md Import the TranscriptClient and use it to fetch a transcript for a given YouTube video ID. Ensure you await client.ready before making requests. ```javascript import TranscriptClient from "youtube-transcript-api"; // both CJS and ESM are supported const client = new TranscriptClient(); (async () => { await client.ready; // wait for client initialization const transcript = await client.getTranscript("dQw4w9WgXcQ"); console.log(transcript); })(); ``` -------------------------------- ### Await TranscriptClient Initialization Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/api-reference/TranscriptClient.md Wait for the client to be fully initialized and ready before making transcript requests. This ensures Firebase configuration credentials have been fetched. ```javascript const client = new TranscriptClient(); // Wait for initialization await client.ready; // Now safe to call methods const transcript = await client.getTranscript("dQw4w9WgXcQ"); ``` -------------------------------- ### Package.json Exports Configuration Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/SOURCE_ANALYSIS.md Configuration in `package.json` to export both ESM and CommonJS entry points. ```json { "main": "./src/index.js", "type": "module", "exports": { "import": "./src/index.js", "require": "./src/index.cjs" } } ``` -------------------------------- ### Bulk Fetch Transcripts for Multiple Videos Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/README.md Demonstrates how to fetch transcripts for multiple YouTube videos efficiently using a single API call. This method is useful for batch processing. ```javascript const transcripts = await client.bulkGetTranscript([ "1E3tv_3D95g", "dQw4w9WgXcQ" ]); console.log(transcripts); ``` ```json [ { "id": "1E3tv_3D95g", "microformat": { "playerMicroformatRenderer": { "category": "Science & Technology", "description": { "simpleText": "Hands on with iOS 26 and everything you need to know from WWDC 2025\n\nMKBHD Merch: http://shop.MKBHD.com\n\nIntro Track: Jordyn Edmonds\nPlaylist of MKBHD Intro music: https://goo.gl/B3AWV5\n\n~\nhttp://twitter.com/MKBHD\nhttp://instagram.com/MKBHD\nhttp://facebook.com/MKBHD\n\n0:00 26 All the Things\n2:01 iOS 16\n5:39 Liquid Glass concerns\n6:35 WatchOS 26\n7:53 tvOS 26\n8:10 macOS Tahoe\n10:55 visionOS 26\n12:48 iPadOS 26\n16:11 What about AI and Siri?" }, "externalChannelId": "UCBJycsmduvYEL83R_U4JriQ", "lengthSeconds": "1102", "ownerChannelName": "Marques Brownlee", "publishDate": "2025-06-10", "title": { "simpleText": "WWDC 2025 Impressions: Liquid Glass!" } } }, "isLive": false, "isLoginRequired": false, "languages": [ { "label": "en", "languageCode": "en" } ], "playabilityStatus": { "status": "OK", "reason": "" }, "title": "WWDC 2025 Impressions: Liquid Glass!", "tracks": [ { "language": "en", "transcript": [ { "start": "0.2", "dur": "3.06", "text": "[Music]" }, { "start": "3.439", "dur": "2.081", "text": "all right So today was Apple's big" }, { "start": "5.52", "dur": "4.079", "text": "software event for 2025 WWDC And it was" }, { "start": "9.599", "dur": "1.841", "text": "a really it was actually a really" }, { "start": "11.44", "dur": "1.279", "text": "interesting one I was kind of wondering" }, ... ] } ] }, ... ] ``` -------------------------------- ### TranscriptClient.ready Property Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/api-reference/TranscriptClient.md A promise that resolves when the client is fully initialized and ready to fetch transcripts. This must be awaited before calling other methods. ```APIDOC ## ready: Promise ### Description A promise that resolves when the client is fully initialized and ready to fetch transcripts. It ensures that Firebase configuration credentials have been successfully scraped. ### Type `Promise` ### Example ```javascript const client = new TranscriptClient(); // Wait for initialization await client.ready; // Now safe to call methods const transcript = await client.getTranscript("dQw4w9WgXcQ"); ``` ``` -------------------------------- ### Custom Configuration for TranscriptClient Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/README.md Initializes the TranscriptClient with custom Axios options, including a specific timeout and a custom User-Agent header. This allows for fine-tuning network requests. ```javascript const client = new TranscriptClient({ timeout: 15000, headers: { "User-Agent": "MyApp/1.0" } }); ``` -------------------------------- ### TranscriptClient Constructor Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/README.md Creates a new instance of the TranscriptClient. You can provide custom Axios configuration options to tailor the client's behavior, such as setting specific headers or timeouts. ```APIDOC ## `new TranscriptClient([AxiosOptions])` Creates a new instance of the `TranscriptClient`. * `AxiosOptions` *(optional)*: Custom Axios configuration object passed to the internal Axios instance. Useful for setting custom headers, timeouts, proxies, etc. See available options [here](https://axios-http.com/docs/req_config) ```js const client = new TranscriptClient({ headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36" } }); ``` ``` -------------------------------- ### Singleton Client Instance Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/USAGE_PATTERNS.md Create a single, reusable client instance to avoid redundant Firebase credential scraping and improve performance through connection pooling. This pattern ensures the client is initialized only once. ```javascript // transcriptClient.js import TranscriptClient from "youtube-transcript-api"; let client = null; export async function getClient() { if (!client) { client = new TranscriptClient(); await client.ready; } return client; } ``` ```javascript import { getClient } from "./transcriptClient.js"; const client = await getClient(); const transcript = await client.getTranscript("dQw4w9WgXcQ"); ``` -------------------------------- ### Handle Transcript Fetching Errors Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/api-reference/TranscriptClient.md Demonstrates how to handle potential errors when fetching a transcript, such as invalid video IDs or client initialization issues. Use a try-catch block to manage exceptions. ```javascript import TranscriptClient from "youtube-transcript-api"; const client = new TranscriptClient(); await client.ready; try { const transcript = await client.getTranscript("invalid_id_12"); } catch (error) { if (error.message === "invalid video ID") { console.log("Video does not exist or is unavailable"); } else if (error.message === "client not fully initialized!") { console.log("Client not ready - did you await client.ready?"); } else { console.error("Unexpected error:", error); } } ``` -------------------------------- ### client.bulkGetTranscript(ids, [config]) Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/README.md Fetches transcripts for multiple YouTube videos in a single request. It takes an array of video IDs and an optional configuration object for Axios requests. ```APIDOC ## client.bulkGetTranscript(ids, [config]) ### Description Fetch transcripts for multiple YouTube videos in a single request. ### Method `client.bulkGetTranscript` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters * `ids` **(string[])** – An array of YouTube video IDs. * `config` **(object)** *(optional)* – Additional Axios request config. See available options [here](https://axios-http.com/docs/req_config) ### Returns * A **Promise** that resolves to an array of transcript objects. ### Errors * `"video not found or unavailable"`: Received status 403 from API. One or more videos could not be found or are unavailable, or a specified video ID does not exist. ### Request Example ```js const transcripts = await client.bulkGetTranscript([ "1E3tv_3D95g", "dQw4w9WgXcQ" ]); console.log(transcripts); ``` ### Response #### Success Response (200) * An array of transcript objects, where each object contains details about the video and its transcript. #### Response Example ```json [ { "id": "1E3tv_3D95g", "microformat": { "playerMicroformatRenderer": { "category": "Science & Technology", "description": { "simpleText": "Hands on with iOS 26 and everything you need to know from WWDC 2025\n\nMKBHD Merch: http://shop.MKBHD.com\n\nIntro Track: Jordyn Edmonds\nPlaylist of MKBHD Intro music: https://goo.gl/B3AWV5\n\n~\nhttp://twitter.com/MKBHD\nhttp://instagram.com/MKBHD\nhttp://facebook.com/MKBHD\n\n0:00 26 All the Things\n2:01 iOS 16\n5:39 Liquid Glass concerns\n6:35 WatchOS 26\n7:53 tvOS 26\n8:10 macOS Tahoe\n10:55 visionOS 26\n12:48 iPadOS 26\n16:11 What about AI and Siri?" }, "externalChannelId": "UCBJycsmduvYEL83R_U4JriQ", "lengthSeconds": "1102", "ownerChannelName": "Marques Brownlee", "publishDate": "2025-06-10", "title": { "simpleText": "WWDC 2025 Impressions: Liquid Glass!" } } }, "isLive": false, "isLoginRequired": false, "languages": [ { "label": "en", "languageCode": "en" } ], "playabilityStatus": { "status": "OK", "reason": "" }, "title": "WWDC 2025 Impressions: Liquid Glass!", "tracks": [ { "language": "en", "transcript": [ { "start": "0.2", "dur": "3.06", "text": "[Music]" }, { "start": "3.439", "dur": "2.081", "text": "all right So today was Apple's big" }, { "start": "5.52", "dur": "4.079", "text": "software event for 2025 WWDC And it was" }, { "start": "9.599", "dur": "1.841", "text": "a really it was actually a really" }, { "start": "11.44", "dur": "1.279", "text": "interesting one I was kind of wondering" }, ... ] } ] } ] ``` ``` -------------------------------- ### bulkGetTranscript Method Configuration Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/SOURCE_ANALYSIS.md The `bulkGetTranscript` method accepts an optional configuration object. This config is merged with constructor configuration and authentication headers. ```javascript bulkGetTranscript(ids, config) ``` -------------------------------- ### Handle YouTube Site Structure Changes Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/errors.md This snippet demonstrates how to catch errors that may occur if YouTube changes its website structure, leading to parsing failures during client initialization. ```javascript import TranscriptClient from "youtube-transcript-api"; const client = new TranscriptClient(); try { // If youtube-transcript.io changes their page structure: await client.ready; // May throw during Firebase config scraping } catch (error) { // Could be: // - TypeError: Cannot read properties of undefined // - SyntaxError: Unexpected token in JSON // - ReferenceError if Function() evaluation fails console.error("Failed to initialize client - site may have changed:", error); } ``` -------------------------------- ### Configure Request Timeout Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/INDEX.md Initializes the TranscriptClient with a custom timeout configuration, setting it to 15 seconds. ```javascript const client = new TranscriptClient({ timeout: 15000 // 15 seconds }); ``` -------------------------------- ### Fetch Transcript with Default Options Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/README.md Retrieves the transcript for a given YouTube video ID using default settings. Ensure the video has available transcripts. ```python from youtube_transcript_api import YouTubeTranscriptApi try: transcriptList = YouTubeTranscriptApi.list_transcripts("dQw4w9WgXcQ") transcript = transcriptList.find_transcript(["en"]) print(transcript.fetch()) except Exception as e: print(e) ``` -------------------------------- ### Retry Failed Requests Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/INDEX.md Illustrates how to implement retries for failed transcript requests. Refer to USAGE_PATTERNS.md for a complete implementation of exponential backoff. ```javascript // See Pattern 3 in USAGE_PATTERNS.md const transcript = await fetchTranscriptWithRetry(client, videoId); ``` -------------------------------- ### Configure Custom HTTP/HTTPS Agents Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/configuration.md Provide custom http.Agent or https.Agent instances for advanced connection pooling and network control. This is useful for managing persistent connections. ```javascript import http from 'http'; import https from 'https'; import TranscriptClient from 'youtube-transcript-api'; const httpAgent = new http.Agent({ keepAlive: true }); const httpsAgent = new https.Agent({ keepAlive: true }); const client = new TranscriptClient({ httpAgent, httpsAgent }); ``` -------------------------------- ### getTranscript Method Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/SOURCE_ANALYSIS.md Fetches a single YouTube video transcript. It obtains authentication, constructs necessary headers including a random X-Hash, and makes a POST request. Handles specific errors like invalid video IDs. ```javascript async getTranscript(id, config) { const auth = await this.#get_auth(); const x_header = await this.#get_x_client_context(id); try { const { data } = await this.#instance.post("/api/transcripts", { ids: [ id ] }, { ...(config || {}), headers: { ...(config?.headers || {}), Authorization: "Bearer " + auth.idToken, [x_header[0]]: x_header[1], 'X-Hash': generateRandomHex(64) } }); return data[0]; } catch (e) { if (e.status == 403) throw new Error('invalid video ID'); else throw e; } } ``` -------------------------------- ### bulkGetTranscript Method Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/README.md Retrieves transcripts for multiple YouTube videos in a single call. This is useful for batch processing and requires the client to be ready. ```APIDOC ## bulkGetTranscript ### Description Fetches transcripts for multiple YouTube videos in a single batch request. ### Method `client.bulkGetTranscript(ids, [config])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **`ids`** (string[]) - Required - An array of YouTube video identifiers. - **`config`** (object) - Optional - Configuration object to override request-level settings such as timeout or headers. ``` -------------------------------- ### TranscriptClient Class Source: https://github.com/0x6a69616e/youtube-transcript-api/blob/main/_autodocs/README.md The main class for interacting with the YouTube Transcript API. It requires initialization and provides methods to fetch transcripts for single or multiple videos. ```APIDOC ## TranscriptClient ### Description The `TranscriptClient` class is the primary interface for interacting with the YouTube Transcript API. It handles initialization, authentication, and fetching transcript data. ### Methods - **`new TranscriptClient([AxiosOptions])`**: Constructor to create a new instance of the client. Optional `AxiosOptions` can be provided for custom HTTP client configuration. - **`client.ready : Promise`**: A promise that resolves when the client has completed its initialization process, including obtaining necessary credentials. This must be awaited before calling other methods. - **`client.getTranscript(id, [config])`**: Fetches the transcript for a single YouTube video identified by its `id`. An optional `config` object can be provided to override request-level settings. - **`client.bulkGetTranscript(ids, [config])`**: Fetches transcripts for multiple YouTube videos specified in an array of `ids`. An optional `config` object can be provided for request-level settings. ```