### Install YouTube.js using NPM, Yarn, or Git Source: https://ytjs.dev/guide/getting-started Provides commands for installing the YouTube.js library using NPM, Yarn, and directly from a Git repository. This allows users to add the library to their projects for various use cases. ```bash # NPM npm install youtubei.js@latest # Yarn yarn add youtubei.js@latest # Git (edge version) npm install github:LuanRT/YouTube.js ``` -------------------------------- ### Install YouTube.js for Deno Source: https://ytjs.dev/guide/getting-started Shows how to install the YouTube.js library for Deno environments using the `deno add` command. It also includes a deprecated import method for older Deno versions. ```typescript # Deno den o add npm:youtubei.js@latest # Deno (deprecated) import { Innertube } from 'https://deno.land/x/youtubei/deno.ts'; ``` -------------------------------- ### Provide Custom JavaScript Interpreter for YouTube.js Source: https://ytjs.dev/guide/getting-started Illustrates how to provide a custom JavaScript interpreter for YouTube.js, which is necessary for features like deciphering streaming URLs. This example uses JavaScript's `Function` constructor to execute obfuscated code. ```typescript import { Innertube, Platform, Types } from 'youtubei.js/web'; Platform.shim.eval = async (data: Types.BuildScriptResult, env: Record) => { const properties = []; if(env.n) { properties.push(`n: exportedVars.nFunction("${env.n}")`) } if (env.sig) { properties.push(`sig: exportedVars.sigFunction("${env.sig}")`) } const code = `${data.output}\nreturn { ${properties.join(', ')} }`; return new Function(code)(); } const innertube = await Innertube.create(/* options */); // ... ``` -------------------------------- ### Basic YouTube.js Usage with Innertube Source: https://ytjs.dev/guide/getting-started Demonstrates the basic usage of the YouTube.js library by creating an instance of the `Innertube` class. This is the entry point for interacting with YouTube's API. ```typescript import { Innertube } from 'youtubei.js'; const innertube = await Innertube.create(/* options */); ``` -------------------------------- ### Browser: Custom Fetch Implementation for YouTube.js Source: https://ytjs.dev/guide/browser-usage Demonstrates how to provide a custom fetch implementation to YouTube.js for browser usage. This allows modification of requests before they are sent, typically for proxying through a server. It takes a RequestInfo or URL and an optional RequestInit object, returning a Promise that resolves to a Response. ```typescript import { Innertube } from 'youtubei.js/web'; await Innertube.create({ fetch: async (input: RequestInfo | URL, init?: RequestInit) => { // Modify the request // and send it to the proxy return fetch(request, init); } }); ``` -------------------------------- ### Cookie Authentication with Innertube Source: https://ytjs.dev/guide/authentication Demonstrates how to authenticate with YouTube using cookie-based authentication. This is the recommended method for most web-based client types. It requires a valid YouTube cookie string. ```javascript const innertube = await Innertube.create({ cookie: '...' }); ``` -------------------------------- ### YouTube TV OAuth2 Authentication Flow Source: https://ytjs.dev/guide/authentication Illustrates the YouTube TV OAuth2 authentication process, which is limited to the TV Innertube client. It involves handling 'auth-pending', 'auth', and 'update-credentials' events, and initiating the sign-in flow. ```javascript innertube.session.on('auth-pending', (data) => { // data.verification_url contains the authorization URL. // data.user_code contains the code to enter on the website. }); innertube.session.on('auth', ({ credentials }) => { // Do something with the credentials, eg; save them to a file. console.log('Sign in successful'); }); // Fired when the access token expires. innertube.session.on('update-credentials', ({ credentials }) => { /** do something with the updated credentials. */ }); await innertube.session.signIn(/* credentials */); ``` -------------------------------- ### Browser: Streaming Videos with YouTube.js and dash.js Source: https://ytjs.dev/guide/browser-usage Shows how to stream YouTube videos in the browser using YouTube.js and dash.js. This involves creating an Innertube instance, fetching video information, converting it to an MPEG-DASH manifest, and then playing it using dash.js. Proxying requests through a server is required for this functionality. ```typescript import { Innertube } from 'youtubei.js/web'; import dashjs from 'dashjs'; const innertube = await Innertube.create({ /* setup - see above */ }); // Get the video info const videoInfo = await innertube.getInfo('videoId', { client: 'TV' }); // now convert to a dash manifest // again - to be able to stream the video in the browser - you must proxy the requests through your own server // to do this, we provide a method to transform the URLs before writing them to the manifest const manifest = await videoInfo.toDash(url => { // modify the url // and return it return url; }); const uri = "data:application/dash+xml;charset=utf-8;base64," + btoa(manifest); const videoElement = document.getElementById('video_player'); const player = dashjs.MediaPlayer().create(); player.initialize(videoElement, uri, true); ``` -------------------------------- ### Caching YouTube OAuth2 Credentials Source: https://ytjs.dev/guide/authentication Shows how to cache YouTube OAuth2 credentials to avoid re-initiating the sign-in flow on subsequent initializations. Note that this practice may have security implications. ```javascript // If you use this, the next call to signIn won't fire 'auth-pending', instead just 'auth' await innertube.session.oauth.cacheCredentials(); ``` -------------------------------- ### Revoking and Removing YouTube OAuth2 Credentials Source: https://ytjs.dev/guide/authentication Provides methods for signing out of the current YouTube session to revoke credentials, or for removing only the cached credentials without signing out. ```javascript await innertube.session.signOut(); // if you don't want to sign out of the current session // and only want to delete the cached credentials, use: await innertube.session.oauth.removeCache(); ``` -------------------------------- ### Call Navigation Endpoint from Parsed Response Source: https://ytjs.dev/guide/advanced-usage This example shows how to call a navigation endpoint found within a parsed YouTube.js response, such as from a button element. It requires `Innertube`, `UniversalCache`, and `YTNodes`. It retrieves an artist's albums and then calls the 'More' button's endpoint to fetch further details. ```typescript import { Innertube, UniversalCache, YTNodes } from 'youtubei.js'; const yt = await Innertube.create({ cache: new UniversalCache(true) }); const artist = await yt.music.getArtist('UC52ZqHVQz5OoGhvbWiRal6g'); const albums = artist.sections[1].as(YTNodes.MusicCarouselShelf); // Let's imagine that we wish to click on the “More” button: const button = albums.as(YTNodes.MusicCarouselShelf).header?.more_content; if (button) { // Having ensured that it exists, we can then call its navigation endpoint using the following code: const page = await button.endpoint.call(yt.actions, { parse: true }); console.info(page); } ``` -------------------------------- ### Parse InnerTube Responses with YouTube.js Parser Source: https://ytjs.dev/guide/advanced-usage This snippet demonstrates the usage of the YouTube.js parser to convert raw InnerTube responses into strongly-typed objects. It requires `Parser`, `YTNodes`, and Node.js `fs` module. The example parses a JSON response representing a YouTube Music artist page and extracts header and content sections. ```typescript // See ./examples/parser import { Parser, YTNodes } from 'youtubei.js'; import { readFileSync } from 'fs'; // YouTube Music's artist page response const data = readFileSync('./artist.json').toString(); const page = Parser.parseResponse(JSON.parse(data)); const header = page.header?.item().as(YTNodes.MusicImmersiveHeader, YTNodes.MusicVisualHeader); console.info('Header:', header); // The parser uses a proxy object to add type safety and utility methods for working with InnerTube's data arrays: const tab = page.contents?.item().as(YTNodes.SingleColumnBrowseResults).tabs.firstOfType(YTNodes.Tab); if (!tab) throw new Error('Target tab not found'); if (!tab.content) throw new Error('Target tab appears to be empty'); const sections = tab.content?.as(YTNodes.SectionList).contents.as(YTNodes.MusicCarouselShelf, YTNodes.MusicDescriptionShelf, YTNodes.MusicShelf); console.info('Sections:', sections); ``` -------------------------------- ### Provide Custom Fetch Implementation in YouTube.js Source: https://ytjs.dev/guide/proxies This snippet demonstrates how to pass a custom fetch implementation to YouTube.js. This custom implementation allows for pre-request modifications or post-response transformations, which is particularly useful for setting up proxies. The provided `fetch` function should return a `Response` object. ```typescript const yt = await Innertube.create({ fetch: async (input: RequestInfo | URL, init?: RequestInit) => { // make the request with your own fetch implementation // and return the response return new Response( /* ... */ ); } }); ``` -------------------------------- ### Create Persistent Universal Cache with YouTube.js Source: https://ytjs.dev/guide/caching Shows how to create a persistent UniversalCache instance for YouTube.js, specifying a directory for storing cached data. This cache will retain data across application restarts. The cache directory will be created if it does not exist. Requires importing `Innertube` and `UniversalCache` from 'youtubei.js'. ```typescript const innertube = await Innertube.create({ cache: new UniversalCache( // Enables persistent caching true, // Path to the cache directory. The directory will be created if it doesn't exist './.cache' ) }); ``` -------------------------------- ### Create Non-Persistent Universal Cache with YouTube.js Source: https://ytjs.dev/guide/caching Demonstrates how to create a non-persistent UniversalCache instance for YouTube.js. This cache does not store data between application runs. It requires importing `Innertube` and `UniversalCache` from 'youtubei.js'. The cache will be stored in the OS's temporary directory or `indexedDB` in browsers. ```typescript import { Innertube, UniversalCache } from 'youtubei.js'; const innertube = await Innertube.create({ cache: new UniversalCache(false) }); ``` -------------------------------- ### Retrieve Video Information using Actions Class Source: https://ytjs.dev/guide/advanced-usage This snippet demonstrates how to fetch video information by using the `Actions` class within YouTube.js. It requires the `Innertube` and `UniversalCache` classes. The function takes a video ID as input and returns parsed video data. ```typescript import { Innertube, UniversalCache } from 'youtubei.js'; const yt = await Innertube.create({ cache: new UniversalCache(true) }); async function getVideoInfo(videoId: string) { const videoInfo = await yt.actions.execute('/player', { // You can add any additional payloads here, and they'll merge with the default payload sent to InnerTube. videoId, client: 'YTMUSIC', // InnerTube client to use. parse: true // tells YouTube.js to parse the response (not sent to InnerTube). }); return videoInfo; } const videoInfo = await getVideoInfo('jLTOuvBTLxA'); console.info(videoInfo); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.