YouTube.js

YouTube.js

YouTube InnerTube API的全功能封装库

YouTube.js是一个全面封装InnerTube API的开源库,支持视频信息获取、搜索、评论、直播聊天等核心功能。它可在Node.js、Deno和现代浏览器中运行,通过模拟实际客户端行为来解析API响应。该库为开发YouTube相关应用提供了简单高效的程序化交互方式。

YouTube.jsInnerTube APINode.js视频信息获取搜索功能Github开源项目
<!-- BADGE LINKS --> <!-- OTHER LINKS --> <div align="center"> <br/> <p> <a href="https://github.com/LuanRT/YouTube.js"><img src="https://luanrt.github.io/assets/img/ytjs.svg" title="youtube.js" alt="YouTube.js' Github Page" width="200" /></a> </p> <p align="center">A full-featured wrapper around the InnerTube API</p>

Discord CI NPM Version Downloads Codefactor

<h5> Sponsored by&nbsp;&nbsp;&nbsp;&nbsp;<a href="https://serpapi.com"><img src="https://luanrt.github.io/assets/img/serpapi.svg" alt="SerpApi - API to get search engine results with ease." height=35 valign="middle"></a> </h5> <br> </div>

InnerTube is an API used by all YouTube clients. It was created to simplify the deployment of new features and experiments across the platform [^1]. This library manages all low-level communication with InnerTube, providing a simple and efficient way to interact with YouTube programmatically. Its design aims to closely emulate an actual client, including the parsing of API responses.

If you have any questions or need help, feel free to reach out to us on our Discord server or open an issue here.

Table of Contents

<ol> <li><a href="#prerequisites">Prerequisites</a></li> <li><a href="#installation">Installation</a></li> <li> <a href="#usage">Usage</a> <ul> <li><a href="#browser-usage">Browser Usage</a></li> <li><a href="#caching">Caching</a></li> <li><a href="#api">API</a></li> <li><a href="#extending-the-library">Extending the library</a></li> </ul> </li> <li><a href="#contributing">Contributing</a></li> <li><a href="#contact">Contact</a></li> <li><a href="#disclaimer">Disclaimer</a></li> <li><a href="#license">License</a></li> </ol>

Prerequisites

YouTube.js runs on Node.js, Deno, and modern browsers.

It requires a runtime with the following features:

  • fetch
    • On Node, we use undici's fetch implementation, which requires Node.js 16.8+. If you need to use an older version, you may provide your own fetch implementation. See providing your own fetch implementation for more information.
    • The Response object returned by fetch must thus be spec compliant and return a ReadableStream object if you want to use the VideoInfo#download method. (Implementations like node-fetch return a non-standard Readable object.)
  • EventTarget and CustomEvent are required.

Installation

# NPM npm install youtubei.js@latest # Yarn yarn add youtubei.js@latest # Git (edge version) npm install github:LuanRT/YouTube.js

When using Deno, you can import YouTube.js directly from deno.land:

import { Innertube } from 'https://deno.land/x/youtubei/deno.ts';

Usage

Create an InnerTube instance:

// const { Innertube } = require('youtubei.js'); import { Innertube } from 'youtubei.js'; const youtube = await Innertube.create(/* options */);

Options

<details> <summary>Click to expand</summary>
OptionTypeDescriptionDefault
langstringLanguage.en
locationstringGeolocation.US
account_indexnumberThe account index to use. This is useful if you have multiple accounts logged in. NOTE: Only works if you are signed in with cookies.0
visitor_datastringSetting this to a valid and persistent visitor data string will allow YouTube to give this session tailored content even when not logged in. A good way to get a valid one is by either grabbing it from a browser or calling InnerTube's /visitor_id endpoint.undefined
po_tokenstringProof of Origin Token. This is an attestation token generated by BotGuard/DroidGuard. It is used to confirm that the request is coming from a genuine device. To obtain a valid token, please refer to Invidious' Trusted Session Generator.undefined
retrieve_playerbooleanSpecifies whether to retrieve the JS player. Disabling this will make session creation faster. NOTE: Deciphering formats is not possible without the JS player.true
enable_safety_modebooleanSpecifies whether to enable safety mode. This will prevent the session from loading any potentially unsafe content.false
generate_session_locallybooleanSpecifies whether to generate the session data locally or retrieve it from YouTube. This can be useful if you need more performance. NOTE: If you are using the cache option and a session has already been generated, this will be ignored. If you want to force a new session to be generated, you must clear the cache or disable session caching.false
enable_session_cachebooleanSpecifies whether to cache the session data.true
device_categoryDeviceCategoryPlatform to use for the session.DESKTOP
client_typeClientTypeInnerTube client type. It is not recommended to change this unless you know what you are doing.WEB
timezonestringThe time zone.*
cacheICacheUsed to cache algorithms, session data, and OAuth2 tokens.undefined
cookiestringYouTube cookies.undefined
fetchFetchFunctionFetch function to use.fetch
</details>

Browser Usage

To use YouTube.js in the browser, you must proxy requests through your own server. You can see our simple reference implementation in Deno at examples/browser/proxy/deno.ts.

You may provide your own fetch implementation to be used by YouTube.js, which we will use to modify and send the requests through a proxy. See examples/browser/web for a simple example using Vite.

// Multiple exports are available for the web. // Unbundled ESM version import { Innertube } from 'youtubei.js/web'; // Bundled ESM version // import { Innertube } from 'youtubei.js/web.bundle'; // Production Bundled ESM version // import { Innertube } from 'youtubei.js/web.bundle.min'; await Innertube.create({ fetch: async (input: RequestInfo | URL, init?: RequestInit) => { // Modify the request // and send it to the proxy // fetch the URL return fetch(request, init); } });

Streaming

YouTube.js supports streaming of videos in the browser by converting YouTube's streaming data into an MPEG-DASH manifest.

The example below uses dash.js to play the video.

import { Innertube } from 'youtubei.js/web'; import dashjs from 'dashjs'; const youtube = await Innertube.create({ /* setup - see above */ }); // Get the video info const videoInfo = await youtube.getInfo('videoId'); // now convert to a dash manifest // again - to be able to stream the video in the browser - we must proxy the requests through our 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);

A fully working example can be found in examples/browser/web.

<a name="custom-fetch"></a>

Providing your own fetch implementation

You may provide your own fetch implementation to be used by YouTube.js. This can be useful in some cases to modify the requests before they are sent and transform the responses before they are returned (eg. for proxies).

// provide a fetch implementation 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( /* ... */ ); } });

<a name="caching"></a>

Caching

Caching the transformed player instance can greatly improve the performance. Our UniversalCache implementation uses different caching methods depending on the environment.

In Node.js, we use the node:fs module, Deno.writeFile() in Deno, and indexedDB in browsers.

By default, the cache stores data in the operating system's temporary directory (or indexedDB in browsers). You can make this cache persistent by specifying the path to the cache directory, which will be created if it doesn't exist.

import { Innertube, UniversalCache } from 'youtubei.js'; // Create a cache that stores files in the OS temp directory (or indexedDB in browsers) by default. const yt = await Innertube.create({ cache: new UniversalCache(false) }); // You may want to create a persistent cache instead (on Node and Deno). const yt = 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' ) });

API

<a name="getinfo"></a>

getInfo(target, client?)

Retrieves video info.

Returns: Promise<VideoInfo>

ParamTypeDescription
targetstring | NavigationEndpointIf string, the id of the video. If NavigationEndpoint, the endpoint of watchable elements such as Video, Mix and Playlist. To clarify, valid endpoints have payloads containing at least videoId and optionally playlistId, params and index.
client?InnerTubeClientInnerTube client to use.
<details> <summary>Methods & Getters</summary> <p>
  • <info>#like()

    • Likes the video.
  • <info>#dislike()

    • Dislikes the video.
  • <info>#removeRating()

    • Removes like/dislike.
  • <info>#getLiveChat()

    • Returns a LiveChat instance.
  • <info>#getTrailerInfo()

    • Returns trailer info in a new VideoInfo instance, or null if none. Typically available for non-purchased movies or films.
  • <info>#chooseFormat(options)

    • Used to choose streaming data formats.
  • <info>#toDash(url_transformer?, format_filter?)

    • Converts streaming data to an MPEG-DASH manifest.
  • <info>#download(options)

  • <info>#getTranscript()

    • Retrieves the video's transcript.
  • <info>#filters

    • Returns filters that can be applied to the watch next feed.
  • <info>#selectFilter(name)

    • Applies the given filter to the watch next feed and returns a new instance of VideoInfo.
  • <info>#getWatchNextContinuation()

    • Retrieves the next batch of items for the watch next feed.
  • <info>#addToWatchHistory()

    • Adds the video to the watch history.
  • <info>#autoplay_video_endpoint

    • Returns the endpoint of the video for Autoplay.
  • <info>#has_trailer

    • Checks if trailer is available.
  • <info>#page

    • Returns original InnerTube response (sanitized).
</p> </details>

<a name="getbasicinfo"></a>

getBasicInfo(video_id, client?)

Suitable for cases where you only need basic video metadata. Also, it is faster than getInfo().

Returns: Promise<VideoInfo>

ParamTypeDescription
video_idstringThe id of the video
client?InnerTubeClientInnerTube client to use.

<a name="search"></a>

search(query, filters?)

Searches the given query on YouTube.

Returns: Promise<Search>

Note Search extends the Feed class.

ParamTypeDescription
querystringThe search query
filters?SearchFiltersSearch filters
<details> <summary>Search Filters</summary>
FilterTypeValueDescription
upload_datestringall | hour | today | week | month | yearFilter by upload date
typestringall | video | channel | playlist | movieFilter by type
durationstringall | short | medium | longFilter by duration
sort_bystringrelevance | rating | upload_date | view_countSort by
featuresstring[]hd |

编辑推荐精选

扣子-AI办公

扣子-AI办公

职场AI,就用扣子

AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!

堆友

堆友

多风格AI绘画神器

堆友平台由阿里巴巴设计团队创建,作为一款AI驱动的设计工具,专为设计师提供一站式增长服务。功能覆盖海量3D素材、AI绘画、实时渲染以及专业抠图,显著提升设计品质和效率。平台不仅提供工具,还是一个促进创意交流和个人发展的空间,界面友好,适合所有级别的设计师和创意工作者。

图像生成AI工具AI反应堆AI工具箱AI绘画GOAI艺术字堆友相机AI图像热门
码上飞

码上飞

零代码AI应用开发平台

零代码AI应用开发平台,用户只需一句话简单描述需求,AI能自动生成小程序、APP或H5网页应用,无需编写代码。

Vora

Vora

免费创建高清无水印Sora视频

Vora是一个免费创建高清无水印Sora视频的AI工具

Refly.AI

Refly.AI

最适合小白的AI自动化工作流平台

无需编码,轻松生成可复用、可变现的AI自动化工作流

酷表ChatExcel

酷表ChatExcel

大模型驱动的Excel数据处理工具

基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。

AI工具酷表ChatExcelAI智能客服AI营销产品使用教程
TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
AIWritePaper论文写作

AIWritePaper论文写作

AI论文写作指导平台

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

AI辅助写作AI工具AI论文工具论文写作智能生成大纲数据安全AI助手热门
博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。

AI办公办公工具AI工具博思AIPPTAI生成PPT智能排版海量精品模板AI创作热门
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

下拉加载更多