Introducing a new way to review your PRs.

Read the announcement

iv-org / invidious

Invidious is an alternative front-end to YouTube

View on GitHub

19 documents · Updated Oct 12, 2026

docs / youtube-backend-integration

YouTube backend integration

The YouTube backend integration is the outbound access layer that lets Invidious request YouTube data and related media without exposing those upstream requests to the browser. It combines shared network access, URL cleanup, client-specific API requests, and conversion of changing YouTube responses into data that the video and channel features can use.

Outbound access boundary

Request and response flow

The access layer sits between Invidious routes and YouTube services. A feature selects an upstream operation, the layer sends the request through a shared client, and the returned data is either passed to a feature parser or streamed back as media. A pasted YouTube URL takes a separate cleanup path before a route uses it.

The main flow is:

flowchart LR
    A[Invidious feature] --> B{Upstream need}
    B -->|YouTube data| C[YouTube API wrapper]
    B -->|URL from user| D[URL sanitizer]
    B -->|Image or media| E[HTTP client pool]
    D --> A
    C --> E
    E --> F[YouTube service]
    F --> G[JSON or media response]
    G --> H[Extracted feature data]

References: src/…/youtube_api.cr• L340-560 src/…/connection_pool.cr• L5-33 src/…/search.cr• L61-65

Client contexts

The API wrapper sends requests as one of several supported YouTube client types. A client context defines the upstream client identity and can include a region so that results follow the requested geographic view. Embed and mobile contexts support feature paths that need YouTube to treat the request as a different viewing surface.

This choice stays with the request that needs it. Search and comments can pass a region-specific context, while common browse calls use the default context. The context also supplies the request headers that identify the selected client to YouTube.

References: src/…/youtube_api.cr• L26-46 src/…/youtube_api.cr• L192-281 src/…/youtube_api.cr• L289-337 src/…/processors.cr• L5-14 src/…/youtube.cr• L4-16

Connection and network access

Shared connection pools

The integration reuses HTTP clients through bounded pools. The main pool serves YouTube requests, image requests can create one pool for each ytimg.com subdomain, and companion services use a separate pool. This limits connection setup and gives concurrent requests a shared capacity instead of creating a new client for every operation.

When a checked-out client fails, the pool closes it and retries the operation with a fresh client. The pool also reapplies proxy settings when a client is checked out because the client may have been returned to the pool after earlier use.

References: src/…/connection_pool.cr• L1-47 src/…/connection_pool.cr• L107-148 src/…/connection_pool.cr• L192-205 src/invidious.cr• L89-97

Proxy and address routing

All normal YouTube and image clients can use the configured outbound proxy. The layer supports HTTP CONNECT proxies and SOCKS5 proxies. SOCKS5 sends host names to the proxy for name lookup, which keeps the proxy in control of the destination lookup and supports region-sensitive routing.

The client can also force IPv4 or IPv6 for outbound access. This setting applies when the service needs a specific address family to avoid a network or rate-limit problem. Requests to an Invidious companion use their own pooled clients and do not use the configured HTTP proxy.

References: src/…/connection_pool.cr• L124-177 src/…/socks_proxy.cr• L1-13 src/…/socks_proxy.cr• L34-60 src/…/config.cr• L161-183

Upstream request defaults

Clients add browser-like YouTube request headers and configured cookies when they contact YouTube hosts. They use bounded connection and read time limits so an upstream stall does not hold a pool slot forever. API requests also accept compressed responses and turn them into text before JSON parsing.

These defaults belong to the access boundary rather than to individual features. This keeps direct page requests, API requests, and image requests aligned when YouTube expects common headers or when deployment settings change.

References: src/…/connection_pool.cr• L107-148 src/…/youtube_api.cr• L572-617 src/…/youtube_api.cr• L681-710

URL handling

User URL normalization

UrlSanitizer turns a user-supplied YouTube URL into the small internal URI form used by Invidious routes. It adds a scheme when needed, removes unsafe path parts, and keeps only query parameters that match the target route. A short youtu.be link becomes a watch URL with its first path part as the video ID.

The sanitizer recognizes separate parameter sets for watch, channel, playlist, and search paths. It drops unrelated parameters instead of allowing them to flow into later route logic. Invalid or unsupported input falls back to the site root.

URL familyPreserved purpose
Watch, embed, shorts, and clipsVideo ID, playlist context, time range, and selected comment
Channel and profile pathsChannel or user lookup values
Playlist and mix pathsPlaylist ID
Search pathsSearch text and search filters

References: src/…/url_sanitizer.cr• L3-17 src/…/url_sanitizer.cr• L36-64 src/…/url_sanitizer.cr• L67-120

YouTube URL resolution

Some channel links do not contain a channel ID. The API wrapper can send such a link to YouTube's URL resolution operation and use the returned browse ID for later channel requests. This separates human-facing channel names and brand links from the stable ID that the browse operations need.

References: src/…/youtube_api.cr• L473-508 src/…/processors.cr• L16-35

Response extraction

Response containers and continuations

YouTube returns related items inside different JSON containers for tabs, search results, and continuation pages. The extraction layer first locates the relevant container, then exposes its raw items to the item parsers. A continuation is a token that identifies the next page or the next part of a result stream.

The same path handles an initial response and a later continuation response. It returns normalized items together with the next token when YouTube provides one, so video and channel features can request more content without knowing the upstream JSON layout.

flowchart TD
    A[YouTube JSON] --> B[Find response content]
    B --> C{Content shape}
    C -->|Tab| D[Unpack tab items]
    C -->|Search| E[Unpack search items]
    C -->|Continuation| F[Unpack appended items]
    D --> G[Parse item types]
    E --> G
    F --> G
    G --> H[Normalized items and next token]

References: src/…/extractors.cr• L926-1086 src/…/extractors.cr• L1148-1217

Normalized item data

The item parser cycle turns YouTube renderer records into shared search and browse data types. It covers videos, channels, playlists, categories, hashtags, short-form items, and continuation tokens. Each parser checks whether a record matches its shape, so a change in one YouTube record type does not require every feature to understand every other type.

Common helper functions fill gaps between YouTube response variants. They read text from either a single text value or a list of text runs, find browse IDs and thumbnails, count videos, and detect verified badges. Missing optional values use feature-safe defaults, while a parser error becomes a problem item that can be logged without stopping the whole item stream.

References: src/…/extractors.cr• L31-49 src/…/extractors.cr• L52-69 src/…/extractors.cr• L180-245 src/…/extractors_utils.cr• L1-29 src/…/extractors_utils.cr• L32-87 src/…/extractors.cr• L1088-1146

YouTube API interactions

API operation families

YoutubeAPI provides a small set of upstream operations that cover the main data flows. Each operation builds the required client context and sends JSON to a YouTube internal API endpoint. Features then decide how to interpret the returned data.

Operation familySystem role
BrowseLoad channel, playlist, tab, and continuation content
NextLoad related data, comments, replies, or another continuation page
SearchReturn region-aware search results
PlayerObtain video playability and streaming metadata through the companion path when enabled
Resolve URLTurn a human-facing YouTube URL into a browse target
TranscriptRequest caption text for a selected language or format

Direct YouTube API failures include non-success HTTP responses and upstream JSON error objects. The wrapper logs the endpoint and error context, then raises an Invidious information error instead of returning an unvalidated response.

References: src/…/youtube_api.cr• L340-560 src/…/youtube_api.cr• L572-637

Invidious companion access

The Invidious companion is an optional upstream service used for player data. When configured, a separate pool selects a companion instance and sends the player request with a bearer key. If no companion is configured, the player operation returns no data and the video feature must handle that unavailable path.

Companion failures cause the wrapper to report a communication error. The companion pool can replace a failed wrapper and select another configured instance, which keeps companion selection separate from direct YouTube access.

References: src/…/youtube_api.cr• L452-471 src/…/youtube_api.cr• L640-679 src/…/connection_pool.cr• L49-105 src/…/config.cr• L179-187

Feature handoffs

Video data retrieval

Video retrieval uses the player operation as its source for playability, video details, captions, storyboards, and streaming data. It can then request the next operation to add watch-page data before the video parser converts the combined response into the model used by watch and playback routes.

For the end-to-end video flow, see Video watch and playback.

References: src/…/parser.cr• L58-135 src/…/parser.cr• L157-229 src/…/youtube_api.cr• L427-471

Channel data retrieval

Channel retrieval uses browse requests for channel tabs and continuation pages. The extraction layer supplies normalized videos, shorts, live streams, playlists, and related items, while channel code supplies the channel name and ID as fallbacks when a continuation omits author details.

For the channel and subscription flows that consume this data, see Channel content and subscriptions.

References: src/…/videos.cr• L11-92 src/…/playlists.cr• L1-55 src/…/youtube_api.cr• L340-389

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the client identity, request headers, and context fields aligned when adding or changing a YouTube API client.
  • Keep every new ytimg.com authority on a pool path so image requests retain proxy and retry behavior.
  • Keep URL query allowlists aligned with the route families that consume sanitized URLs.
  • Keep new response containers connected to both the container extractor and the item parser that consumes their records.
  • Keep continuation-producing feature code aligned with extract_items so the next token is not lost between pages.
  • Keep companion key and instance changes aligned with the separate companion pool and its no-proxy rule.

Important failure modes

TriggerConsequenceGuard
YouTube returns a non-200 response or a JSON error objectThe feature receives an information error instead of data_post_json checks the status and the parsed error field
A pooled HTTP client fails during a requestThe current client is discarded and the request is retried with a new clientYoutubeConnectionPool#client replaces the failed client
The configured proxy type is not HTTP, SOCKS5, or SOCKS5hClient setup fails before the outbound requestconfigure_proxy rejects unsupported proxy types
A URL contains unsupported query parameters or unsafe path partsThe route receives a reduced URI or a root redirectUrlSanitizer.process applies route-specific allowlists and path filtering
YouTube changes a renderer shape that has no matching parserThe item can be skipped or represented as a problematic itemThe extractor cycles through known parsers and logs parse failures
YouTube returns a video different from the requested IDVideo data is rejected as unavailableVideo parsing checks the returned videoDetails.videoId
No Invidious companion is configuredPlayer data is unavailable through this access pathYoutubeAPI.player returns nil, which the video flow must handle

Key files

FileWhy to read it
src/invidious/yt_backend/connection_pool.crShows the shared YouTube, image, and companion network boundary.
src/invidious/yt_backend/socks_proxy.crShows the SOCKS5 transport option and its host-name routing behavior.
src/invidious/yt_backend/youtube_api.crDefines the client contexts and the main YouTube API operation families.
src/invidious/yt_backend/url_sanitizer.crDefines the accepted URL shapes and query parameter rules.
src/invidious/yt_backend/extractors.crShows how changing YouTube response containers become normalized items.
src/invidious/yt_backend/extractors_utils.crDefines shared rules for text, badges, counts, thumbnails, and browse IDs.
src/invidious/videos/parser.crShows the handoff from player and next responses to video data.
src/invidious/channels/videos.crShows how channel video tabs use browse results and continuations.
src/invidious/channels/playlists.crShows how channel playlist-like tabs use browse results.