### Install youtube-transcript-plus using npm Source: https://context7.com/ericmmartin/youtube-transcript-plus/llms.txt Installs the youtube-transcript-plus library using npm. This is the first step to using the library in a Node.js project. ```bash npm install youtube-transcript-plus ``` -------------------------------- ### Install youtube-transcript-plus using npm or yarn Source: https://github.com/ericmmartin/youtube-transcript-plus/blob/main/README.md This snippet shows how to install the youtube-transcript-plus library using either npm or yarn package managers. These commands are essential for setting up the library in your Node.js project. ```bash $ npm install youtube-transcript-plus ``` ```bash $ yarn add youtube-transcript-plus ``` -------------------------------- ### Fetch YouTube Transcript with In-Memory Cache (TypeScript) Source: https://github.com/ericmmartin/youtube-transcript-plus/blob/main/README.md Shows how to use the `InMemoryCache` strategy for caching transcripts. This example sets a Time-To-Live (TTL) of 30 minutes for the cache entries. ```typescript import { fetchTranscript, InMemoryCache } from 'youtube-transcript-plus'; fetchTranscript('videoId_or_URL', { lang: 'en', userAgent: 'FOO', cache: new InMemoryCache(1800000), // 30 minutes TTL }) .then(console.log) .catch(console.error); ``` -------------------------------- ### Fetch YouTube Transcript - Basic Usage (JavaScript) Source: https://github.com/ericmmartin/youtube-transcript-plus/blob/main/README.md Demonstrates the basic usage of the `fetchTranscript` function to retrieve a YouTube video's transcript. It takes a video ID or URL as input and logs the transcript to the console. This is the simplest way to get started with the library. ```javascript import { fetchTranscript } from 'youtube-transcript-plus'; // Fetch transcript using default settings fetchTranscript('videoId_or_URL').then(console.log).catch(console.error); ``` -------------------------------- ### Fetch YouTube Transcript with File System Cache (TypeScript) Source: https://github.com/ericmmartin/youtube-transcript-plus/blob/main/README.md Demonstrates using the `FsCache` strategy for caching transcripts to the file system. This example specifies a cache directory and a TTL of 1 day. ```typescript import { fetchTranscript, FsCache } from 'youtube-transcript-plus'; fetchTranscript('videoId_or_URL', { cache: new FsCache('./my-cache-dir', 86400000), // 1 day TTL }) .then(console.log) .catch(console.error); ``` -------------------------------- ### TypeScript Error Handling Example Source: https://github.com/ericmmartin/youtube-transcript-plus/blob/main/CLAUDE.md Demonstrates a common error handling pattern in TypeScript for the youtube-transcript-plus library. It shows how to use a try-catch block to gracefully handle specific errors like 'YoutubeTranscriptVideoUnavailableError'. ```typescript try { const transcript = await fetchTranscript(videoId); } catch (error) { if (error instanceof YoutubeTranscriptVideoUnavailableError) { // Handle unavailable video } // Handle other specific error types } ``` -------------------------------- ### TypeScript Interface and Example for Transcript Response Source: https://context7.com/ericmmartin/youtube-transcript-plus/llms.txt Defines the TypeScript interface for a transcript response segment, including text, duration, offset, and optional language. Also provides an example array of segments and demonstrates common operations like joining text, summing durations, and finding a segment by time. ```typescript interface TranscriptResponse { text: string; // The transcript text for this segment duration: number; // Duration in seconds offset: number; // Start time offset in seconds lang?: string; // Language code of the transcript } // Example response structure const segments = [ { text: "Hello and welcome", duration: 1.5, offset: 0.0, lang: "en" }, { text: "to this video", duration: 1.2, offset: 1.5, lang: "en" }, { text: "Today we'll discuss", duration: 2.0, offset: 2.7, lang: "en" }, ]; // Common operations with transcript data const fullText = segments.map(s => s.text).join(' '); const totalDuration = segments.reduce((sum, s) => sum + s.duration, 0); const segmentAtTime = (seconds) => segments.find(s => seconds >= s.offset && seconds < s.offset + s.duration ); ``` -------------------------------- ### Fetch YouTube Transcript in a Specific Language (JavaScript) Source: https://github.com/ericmmartin/youtube-transcript-plus/blob/main/README.md Demonstrates how to specify the desired language for the transcript using the `lang` option. This example shows fetching the transcript in French ('fr'). ```javascript fetchTranscript('videoId_or_URL', { lang: 'fr', // Fetch transcript in French }) .then(console.log) .catch(console.error); ``` -------------------------------- ### Fetch YouTube Transcript with Custom Fetch Functions (JavaScript) Source: https://github.com/ericmmartin/youtube-transcript-plus/blob/main/README.md Provides an example of injecting custom `videoFetch`, `playerFetch`, and `transcriptFetch` functions to modify the fetching behavior. This allows for advanced use cases like using proxies or custom headers for each type of HTTP request made by the library. ```javascript fetchTranscript('videoId_or_URL', { videoFetch: async ({ url, lang, userAgent }) => { // Custom logic for video page fetch (GET) return fetch(`https://my-proxy-server.com/?url=${encodeURIComponent(url)}`, { headers: { ...(lang && { 'Accept-Language': lang }), 'User-Agent': userAgent, }, }); }, playerFetch: async ({ url, method, body, headers, lang, userAgent }) => { // Custom logic for Innertube API call (POST) return fetch(`https://my-proxy-server.com/?url=${encodeURIComponent(url)}`, { method, headers: { ...(lang && { 'Accept-Language': lang }), 'User-Agent': userAgent, ...headers, }, body, }); }, transcriptFetch: async ({ url, lang, userAgent }) => { // Custom logic for transcript data fetch (GET) return fetch(`https://my-proxy-server.com/?url=${encodeURIComponent(url)}`, { headers: { ...(lang && { 'Accept-Language': lang }), 'User-Agent': userAgent, }, }); }, }) .then(console.log) .catch(console.error); ``` -------------------------------- ### TypeScript Caching Strategy Interface Source: https://github.com/ericmmartin/youtube-transcript-plus/blob/main/CLAUDE.md Defines the expected structure for custom caching strategies in the youtube-transcript-plus library. Custom implementations must adhere to this interface, providing 'get' and 'set' methods. ```typescript // Assuming CacheStrategy interface is defined elsewhere // Example of implementing a custom cache strategy: class MyCustomCache { async get(key: string): Promise { // Implementation to retrieve data from cache return null; } async set(key: string, value: string): Promise { // Implementation to store data in cache } } const config: TranscriptConfig = { cache: new MyCustomCache() }; ``` -------------------------------- ### Build and Test Commands for youtube-transcript-plus Source: https://github.com/ericmmartin/youtube-transcript-plus/blob/main/CLAUDE.md This snippet lists common npm commands for building, testing, and formatting the project. It includes commands for initiating builds, running Jest tests (including watch mode), and applying code formatting with Prettier. ```bash npm run build npm test npm run test:watch npm run format ``` -------------------------------- ### Implement Custom CacheStrategy with Redis Source: https://context7.com/ericmmartin/youtube-transcript-plus/llms.txt Demonstrates how to implement the CacheStrategy interface for custom caching solutions, specifically using Redis. This allows for persistent or distributed caching of transcripts. It requires a Redis client instance. ```typescript import { fetchTranscript, CacheStrategy } from 'youtube-transcript-plus'; class RedisCache implements CacheStrategy { private redis: any; // Your Redis client constructor(redisClient: any) { this.redis = redisClient; } async get(key: string): Promise { return await this.redis.get(key); } async set(key: string, value: string, ttl?: number): Promise { if (ttl) { await this.redis.setex(key, Math.floor(ttl / 1000), value); } else { await this.redis.set(key, value); } } } // Usage const transcript = await fetchTranscript('dQw4w9WgXcQ', { cache: new RedisCache(redisClient), cacheTTL: 3600000, // 1 hour }); ``` -------------------------------- ### Implement Custom Cache Strategy (TypeScript) Source: https://github.com/ericmmartin/youtube-transcript-plus/blob/main/README.md Illustrates how to implement a custom caching strategy by creating a class that adheres to the `CacheStrategy` interface. This allows for complete control over how transcripts are cached, going beyond the provided in-memory and file system options. ```typescript import { fetchTranscript, CacheStrategy } from 'youtube-transcript-plus'; class CustomCache implements CacheStrategy { async get(key: string): Promise { // Custom logic } async set(key: string, value: string, ttl?: number): Promise { // Custom logic } } fetchTranscript('videoId_or_URL', { cache: new CustomCache(), }) .then(console.log) .catch(console.error); ``` -------------------------------- ### Configure Transcript Fetching Options (TypeScript) Source: https://context7.com/ericmmartin/youtube-transcript-plus/llms.txt Demonstrates how to configure transcript fetching with various options. This includes specifying the language, user agent, disabling HTTPS, setting cache TTL, and providing custom fetch functions for different request types. ```typescript import { fetchTranscript } from 'youtube-transcript-plus'; const transcript = await fetchTranscript('dQw4w9WgXcQ', { lang: 'en', // Language code for transcript userAgent: 'Custom UA/1.0', // Custom User-Agent string disableHttps: false, // Use HTTP instead of HTTPS cache: undefined, // CacheStrategy implementation cacheTTL: 3600000, // Cache time-to-live in milliseconds (1 hour default) videoFetch: undefined, // Custom fetch for video page (GET) playerFetch: undefined, // Custom fetch for Innertube API (POST) transcriptFetch: undefined, // Custom fetch for transcript data (GET) }); ``` -------------------------------- ### Use YoutubeTranscript Class for Reusable Fetcher Instances Source: https://context7.com/ericmmartin/youtube-transcript-plus/llms.txt Presents an alternative class-based API for creating reusable transcript fetcher instances with pre-configured settings like language, cache, and user agent. This approach simplifies fetching transcripts for multiple videos with consistent options. ```javascript import { YoutubeTranscript, InMemoryCache } from 'youtube-transcript-plus'; // Create instance with default config const fetcher = new YoutubeTranscript({ lang: 'en', cache: new InMemoryCache(3600000), userAgent: 'MyApp/1.0', }); // Fetch transcripts using instance method const transcript1 = await fetcher.fetchTranscript('dQw4w9WgXcQ'); const transcript2 = await fetcher.fetchTranscript('another-video-id'); // Or use static method directly const transcript3 = await YoutubeTranscript.fetchTranscript('dQw4w9WgXcQ', { lang: 'es', }); ``` -------------------------------- ### Override Fetch Functions for Proxy Integration Source: https://context7.com/ericmmartin/youtube-transcript-plus/llms.txt Shows how to customize the library's default network request functions (video page, player API, transcript) using custom fetch implementations. This is useful for integrating proxies, adding custom headers, or logging requests. It utilizes the 'https-proxy-agent' library. ```javascript import { fetchTranscript } from 'youtube-transcript-plus'; import { HttpsProxyAgent } from 'https-proxy-agent'; const proxyUrl = 'http://proxy.example.com:8080'; const agent = new HttpsProxyAgent(proxyUrl); async function fetchViaProxy() { const transcript = await fetchTranscript('dQw4w9WgXcQ', { videoFetch: async ({ url, lang, userAgent }) => { console.log('Fetching video page:', url); return fetch(url, { headers: { ...(lang && { 'Accept-Language': lang }), 'User-Agent': userAgent, }, agent: agent, }); }, playerFetch: async ({ url, method, body, headers, lang, userAgent }) => { console.log('Calling Innertube API:', url); return fetch(url, { method, headers: { 'User-Agent': userAgent, ...(lang && { 'Accept-Language': lang }), ...headers, }, body, agent: agent, }); }, transcriptFetch: async ({ url, lang, userAgent }) => { console.log('Fetching transcript:', url); return fetch(url, { headers: { ...(lang && { 'Accept-Language': lang }), 'User-Agent': userAgent, }, agent: agent, }); }, }); return transcript; } ``` -------------------------------- ### TypeScript Custom Fetch Function Implementation Source: https://github.com/ericmmartin/youtube-transcript-plus/blob/main/CLAUDE.md Illustrates how to implement custom fetch functions for video and transcript data within the youtube-transcript-plus library. This is useful for scenarios requiring proxying or custom network logic. ```typescript const config: TranscriptConfig = { videoFetch: async ({ url, lang, userAgent }) => { // Custom logic for video page fetch }, transcriptFetch: async ({ url, lang, userAgent }) => { // Custom logic for transcript fetch } }; ``` -------------------------------- ### Fetch YouTube Transcript with Custom User-Agent (JavaScript) Source: https://github.com/ericmmartin/youtube-transcript-plus/blob/main/README.md Shows how to specify a custom `userAgent` string when fetching a YouTube transcript. This allows you to mimic different browsers or devices, which can be useful for bypassing certain restrictions or for testing purposes. ```javascript fetchTranscript('videoId_or_URL', { userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', }) .then(console.log) .catch(console.error); ``` -------------------------------- ### Fetch YouTube Transcript with HTTP Enabled (JavaScript) Source: https://github.com/ericmmartin/youtube-transcript-plus/blob/main/README.md Illustrates how to disable HTTPS and use HTTP for YouTube requests by setting the `disableHttps` option to `true`. This might be necessary in environments with restricted HTTPS connections, but it is not recommended for production due to security risks. ```javascript fetchTranscript('videoId_or_URL', { disableHttps: true, // Use HTTP instead of HTTPS }) .then(console.log) .catch(console.error); ``` -------------------------------- ### Implement File System Cache for Transcripts (JavaScript) Source: https://context7.com/ericmmartin/youtube-transcript-plus/llms.txt Shows how to use the FsCache for persistent caching of transcripts to the file system. This is useful for server applications where cache persistence across restarts is needed. The cache is configured with a directory and TTL. ```javascript import { fetchTranscript, FsCache } from 'youtube-transcript-plus'; async function fetchWithFileCache() { // Create cache with custom directory and 24-hour TTL const cache = new FsCache('./transcript-cache', 86400000); const transcript = await fetchTranscript('dQw4w9WgXcQ', { cache: cache, }); // Cache files stored as: ./transcript-cache/yt:transcript:dQw4w9WgXcQ:en console.log('Transcript cached to filesystem:', transcript.length, 'segments'); } ``` -------------------------------- ### Implement Error Handling with Specific Exception Types Source: https://context7.com/ericmmartin/youtube-transcript-plus/llms.txt Illustrates how to handle various potential errors during transcript fetching using specific error classes provided by the library. This allows for more granular control over error responses and user feedback. It catches exceptions like VideoUnavailable, Disabled, NotAvailable, TooManyRequests, and InvalidVideoId. ```javascript import { fetchTranscript, YoutubeTranscriptVideoUnavailableError, YoutubeTranscriptDisabledError, YoutubeTranscriptNotAvailableError, YoutubeTranscriptNotAvailableLanguageError, YoutubeTranscriptTooManyRequestError, YoutubeTranscriptInvalidVideoIdError, } from 'youtube-transcript-plus'; async function fetchWithErrorHandling(videoId) { try { const transcript = await fetchTranscript(videoId, { lang: 'en' }); return { success: true, data: transcript }; } catch (error) { if (error instanceof YoutubeTranscriptVideoUnavailableError) { return { success: false, error: 'Video not found or removed' }; } if (error instanceof YoutubeTranscriptDisabledError) { return { success: false, error: 'Transcripts disabled by video owner' }; } if (error instanceof YoutubeTranscriptNotAvailableError) { return { success: false, error: 'No transcripts available for this video' }; } if (error instanceof YoutubeTranscriptNotAvailableLanguageError) { return { success: false, error: error.message }; // Includes available languages } if (error instanceof YoutubeTranscriptTooManyRequestError) { return { success: false, error: 'Rate limited - try again later or use proxy' }; } if (error instanceof YoutubeTranscriptInvalidVideoIdError) { return { success: false, error: 'Invalid video ID or URL format' }; } throw error; // Re-throw unexpected errors } } // Usage const result = await fetchWithErrorHandling('dQw4w9WgXcQ'); if (result.success) { console.log('Got', result.data.length, 'transcript segments'); } else { console.error('Failed:', result.error); } ``` -------------------------------- ### Handle YouTube Transcript Errors in JavaScript Source: https://github.com/ericmmartin/youtube-transcript-plus/blob/main/README.md Demonstrates how to catch and handle specific errors thrown by the youtube-transcript-plus library when fetching video transcripts. It imports custom error types and uses `instanceof` checks to differentiate between various failure scenarios like unavailable videos, disabled transcripts, or missing languages. ```javascript import { YoutubeTranscriptVideoUnavailableError, YoutubeTranscriptDisabledError, YoutubeTranscriptNotAvailableError, YoutubeTranscriptNotAvailableLanguageError, } from 'youtube-transcript-plus'; fetchTranscript('videoId_or_URL') .then(console.log) .catch((error) => { if (error instanceof YoutubeTranscriptVideoUnavailableError) { console.error('Video is unavailable:', error.message); } else if (error instanceof YoutubeTranscriptDisabledError) { console.error('Transcripts are disabled for this video:', error.message); } else if (error instanceof YoutubeTranscriptNotAvailableError) { console.error('No transcript available:', error.message); } else if (error instanceof YoutubeTranscriptNotAvailableLanguageError) { console.error('Transcript not available in the specified language:', error.message); } else { console.error('An unexpected error occurred:', error.message); } }); ``` -------------------------------- ### Fetch Transcript API Source: https://github.com/ericmmartin/youtube-transcript-plus/blob/main/README.md Fetches the transcript for a YouTube video using its ID or URL. Supports various configuration options for language, caching, and custom fetch functions. ```APIDOC ## GET /fetchTranscript ### Description Fetches the transcript for a YouTube video. ### Method GET ### Endpoint /fetchTranscript ### Parameters #### Path Parameters None #### Query Parameters - **videoId** (string) - Required - The YouTube video ID or URL. - **config** (object) - Optional - Configuration object for fetching the transcript. - **lang** (string) - Optional - Language code (e.g., 'en', 'fr') for the transcript. - **userAgent** (string) - Optional - Custom User-Agent string. - **cache** (object) - Optional - Custom caching strategy. - **cacheTTL** (number) - Optional - Time-to-live for cache entries in milliseconds. - **disableHttps** (boolean) - Optional - Set to `true` to use HTTP instead of HTTPS for YouTube requests. - **videoFetch** (function) - Optional - Custom fetch function for the video page request (GET). - **playerFetch** (function) - Optional - Custom fetch function for the YouTube Innertube API request (POST). - **transcriptFetch** (function) - Optional - Custom fetch function for the transcript data request (GET). ### Request Example ```javascript fetchTranscript('dQw4w9WgXcQ', { lang: 'en', cacheTTL: 1800000 // 30 minutes }) ``` ### Response #### Success Response (200) - **transcript** (array) - An array of transcript segment objects. - **text** (string) - The text of the transcript segment. - **duration** (number) - The duration of the segment in seconds. - **offset** (number) - The start time of the segment in seconds. - **lang** (string) - The language of the transcript. #### Response Example ```json [ { "text": "Hello world!", "duration": 1.5, "offset": 0.5, "lang": "en" } ] ``` ## Errors The library throws the following errors: - **`YoutubeTranscriptVideoUnavailableError`**: The video is unavailable or has been removed. - **`YoutubeTranscriptDisabledError`**: Transcripts are disabled for the video. - **`YoutubeTranscriptNotAvailableError`**: No transcript is available for the video. - **`YoutubeTranscriptNotAvailableLanguageError`**: The transcript is not available in the specified language. - **`YoutubeTranscriptInvalidVideoIdError`**: The provided video ID or URL is invalid. ``` -------------------------------- ### Implement In-Memory Cache for Transcripts (JavaScript) Source: https://context7.com/ericmmartin/youtube-transcript-plus/llms.txt Demonstrates using the built-in InMemoryCache to store transcript data. This cache has a Time-To-Live (TTL) and automatically expires entries. Subsequent calls with the same video and configuration will retrieve data from the cache, reducing API calls. ```javascript import { fetchTranscript, InMemoryCache } from 'youtube-transcript-plus'; async function fetchWithMemoryCache() { // Create cache with 30-minute TTL const cache = new InMemoryCache(1800000); // First call fetches from YouTube const transcript1 = await fetchTranscript('dQw4w9WgXcQ', { cache: cache, lang: 'en', }); // Second call returns cached result (no API call) const transcript2 = await fetchTranscript('dQw4w9WgXcQ', { cache: cache, lang: 'en', }); console.log('Transcripts match:', JSON.stringify(transcript1) === JSON.stringify(transcript2)); } ``` -------------------------------- ### Fetch YouTube Transcript using video ID or URL (JavaScript) Source: https://context7.com/ericmmartin/youtube-transcript-plus/llms.txt Fetches a transcript for a given YouTube video ID or URL. Returns an array of transcript segments, each containing text, duration, offset, and language. Supports basic usage with just the video identifier. ```javascript import { fetchTranscript } from 'youtube-transcript-plus'; // Basic usage with video ID const transcript = await fetchTranscript('dQw4w9WgXcQ'); console.log(transcript); // Output: [ // { text: "We're no strangers to love", duration: 2.5, offset: 18.0, lang: 'en' }, // { text: "You know the rules and so do I", duration: 2.8, offset: 20.5, lang: 'en' }, // ... // ] // With full YouTube URL const transcript2 = await fetchTranscript('https://www.youtube.com/watch?v=dQw4w9WgXcQ'); ``` -------------------------------- ### Fetch Transcript in a Specific Language (JavaScript) Source: https://context7.com/ericmmartin/youtube-transcript-plus/llms.txt Fetches a transcript in a specified language (e.g., French). If the requested language is not available, it catches a specific error and logs the available language options provided in the error message. ```javascript import { fetchTranscript } from 'youtube-transcript-plus'; async function getTranscriptInLanguage() { try { // Fetch transcript in French const transcript = await fetchTranscript('zIwLWfaAg-8', { lang: 'fr' }); console.log('French transcript:', transcript); } catch (error) { if (error.name === 'YoutubeTranscriptNotAvailableLanguageError') { // Error message includes available languages console.error(error.message); // "No transcripts are available in "fr" for video "xyz". Available languages: en, es, de" } } } ```