HTTP middleware and static assets
The HTTP boundary prepares each request, applies shared safety and access rules, serves site assets, and turns failures into useful responses before feature routes handle the request. It also adds common response policy, compression, request logs, and URL helpers around the web and API route families described in Application bootstrap and routing and Web and API route families.
Request boundary
The request boundary is the shared context that feature routes receive. It keeps route code focused on product work by loading request state and applying response rules in one place.
Request context
Invidious::Routes::BeforeAll builds the request context before route handling. It reads the PREFS cookie or the browser language, checks a signed-in session when one is present, and stores preferences, user data, session data, and request page data for later use.
The same step applies request-wide response headers. It sets browser safety rules, limits framing to embed pages, controls where media may load, and adds strict transport rules when HTTPS policy requires them. Some paths bypass user lookup because they serve media, images, downloads, API resources, or companion traffic. Web pages and API routes then rely on the shared preference context for locale and related request settings instead of loading them again.
References: src/…/before_all.cr• L14-81 src/…/before_all.cr• L83-147 src/…/authenticated.cr• L14-18 src/…/watch.cr• L4-7
Handler policies
The handler chain adds rules that apply to groups of requests instead of to one route. API requests can receive cross-origin access, protected API requests can use a token or session, disabled video-related API calls can be blocked, and normal pages can receive a frame deny rule while embed pages remain available.
These handlers pass requests to the next stage when their path does not match. This keeps the shared rules narrow and lets the route families retain control of their own responses. The API path is also kept outside the normal HTML error path so that API clients receive API-shaped errors. API route handlers keep that contract by returning JSON for both successful data and route-level failures.
References: src/…/handlers.cr• L22-35 src/…/handlers.cr• L46-71 src/…/handlers.cr• L74-121 src/…/handlers.cr• L123-164 src/…/channels.cr• L4-14 src/…/videos.cr• L16-26
Request flow
The server combines shared setup, path policies, asset lookup, route dispatch, and response work into one request path. This diagram shows the main choices before a feature route produces the final response.
flowchart TD
A[HTTP request] --> B[Shared context and response policy]
B --> C[Path-specific handlers]
C --> D{Matching static asset?}
D -- Yes --> E[Asset response]
D -- No --> F[Feature or API route]
F --> G{Route or request error?}
G -- No --> H[Compressed response and request log]
G -- Yes --> I[HTML, JSON, Atom, or redirect error]
E --> H
I --> H
Response compression
FilteredCompressHandler compresses responses when the client accepts a supported encoding. It skips media, image, storyboard, and selected notification or form responses where compression is not useful or could interfere with the response contract. The asset handler therefore serves the file body while the shared response layer decides whether to compress it. Manifest and API responses keep their own content types while passing through the common policy when they are not excluded.
References: src/…/handlers.cr• L64-71 src/invidious.cr• L215-226 src/…/manifest.cr• L3-5 spec/…/static_assets_handler_spec.cr• L122-199
Request logging
Invidious::LogHandler measures the full request path through the server and records the status, method, URL, and elapsed time. At normal log levels it removes search query details from requests that look like searches, which reduces exposure of user search terms while retaining more detail at debug and trace levels.
References: src/…/logger.cr• L14-39 src/…/logger.cr• L58-70
Error handling
Error handling keeps browser pages, feeds, and API clients on the response format that they expect. It also uses failed page requests as a chance to recover known short paths instead of returning a plain missing-page result.
Error response formats
The shared error helpers produce HTML, Atom, or JSON responses with the right status and content type. Browser errors use the localized error page and may offer a refresh, an instance switch, the matching YouTube page, or issue-report details. API errors return a JSON object, while Atom clients receive an Atom-compatible error body.
The 500 handler uses the HTML error path for normal pages. API routes stay outside that handler through the route exclusion rules, so API code can keep its JSON contract. Authentication failures also return JSON with status 403 before the protected API route runs. Route families use the same contract for upstream failures such as missing videos, channels, feeds, or captions.
References: src/invidious.cr• L207-213 src/…/handlers.cr• L46-61 src/…/handlers.cr• L104-119 src/…/errors.cr• L37-101 src/…/errors.cr• L112-176 src/…/feeds.cr• L10-14 src/…/videos.cr• L16-22
Not-found redirects
The 404 route tries to recover a request that looks like a short video or channel path. It checks the upstream page when needed, then redirects to the local channel or watch page. If it cannot identify the item, it sends the user to the home page.
This behavior makes old or shorthand links useful without changing the normal route map. A special storyboard redirect also supports deployments that do not have a configured public host URL.
References: src/…/errors.cr• L1-51
Static asset delivery
Static asset delivery serves the files that make up the site shell, such as style sheets, scripts, images, and fonts. The asset path is separate from feature routes and falls through to normal routing when no asset matches.
Asset path handling
Invidious::HttpServer::StaticAssetsHandler serves files from the assets public directory with directory listings disabled. It accepts normal file reads and supports the HTTP range rules needed by clients that request only part of a file. Unknown paths continue through the request chain so the application can apply its normal route or 404 behavior.
The server uses the custom asset handler on supported Crystal versions. Older versions use the framework static-file path with the same public directory and long-lived cache header policy.
References: src/invidious.cr• L224-233 src/…/static_assets_handler.cr• L3-12 src/…/kemal_static_file_handler.cr• L121-215
Asset caching
The asset handler keeps small files in memory and limits the total cache to 5 MB. A cached file keeps its body and modification time, so later requests avoid repeated disk reads while still supporting cache validation and range responses. Files that do not fit remain available from disk without expanding the cache.
Asset responses advertise a long cache lifetime and retain the file MIME type. Full and partial responses work with the compression layer, so clients can request a complete asset or selected byte ranges and still receive the response form allowed by the surrounding handlers.
References: src/…/static_assets_handler.cr• L22-46 src/…/static_assets_handler.cr• L48-110 src/…/static_assets_handler.cr• L112-119 spec/…/static_assets_handler_spec.cr• L65-119 spec/…/static_assets_handler_spec.cr• L122-229
Server utilities
The HTTP server utilities provide small, shared transformations that keep URL and request behavior consistent across route families. They support proxy links, safe return paths, host URLs, and byte ranges without owning product-level route behavior.
Proxy URL helpers
Invidious::HttpServer::Utils adds the source host and an optional region to a video proxy URL. It can return either the request target or a URL rooted at the configured public host. A second helper appends query parameters to an existing string or URI without replacing its current query.
These helpers let proxy, manifest, watch, and playback routes share one URL shape. Changes to them can affect links consumed by browsers, media clients, and companion services.
References: src/…/utils.cr• L3-39 src/…/manifest.cr• L35-50 src/…/video_playback.cr• L108-114 src/…/watch.cr• L114-122
Request target helpers
Shared request helpers build the public host URL, reduce return paths to safe local targets, and parse byte ranges for streamed responses. The playback route uses the range result to divide large media responses into bounded requests. Watch actions use the return-path result when they send a user back after an action.
References: src/…/utils.cr• L217-273 src/…/utils.cr• L310-325 src/…/video_playback.cr• L126-151 src/…/watch.cr• L208-261
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the path exclusions in
src/invidious/helpers/handlers.craligned with the response format of every API, media, image, and notification endpoint. A missing exclusion can turn a JSON or media response into HTML or compressed output that the client cannot use. - Keep the request context keys created by
BeforeAllaligned with the data read by templates and route handlers. A change to session or preference loading can alter both authentication and page language or theme. - Keep the CSP companion and media source rules aligned with companion URLs and the local video preference. A mismatch can block playback even when the proxy route returns a valid response.
- Keep the asset cache limit, cache headers, and range behavior aligned with the deployment’s asset update process. Long-lived browser caches can retain an old site shell after an asset change.
- Keep the proxy URL shape stable across
Utils, manifest routes, playback routes, and companion consumers. The host and region query values affect where media requests are sent. - Keep API route error paths aligned with the API exclusion rules. A new route that raises outside the JSON path can silently change a client-visible error from JSON to HTML.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
A bad PREFS cookie or invalid language value | The request falls back to default preferences instead of stopping page delivery. | BeforeAll rescues preference parsing and starts with empty preferences. |
| A session cookie begins with the token prefix used for API tokens | The request is rejected rather than treating an API token as a browser session. | Session loading rejects the token prefix before database lookup. |
| A protected API request has no valid token or session | The route is not called and the client receives a JSON 403 response. | AuthHandler requires an authenticated user before call_next. |
| A static path contains a NUL byte | The asset request returns a bad-request response instead of reaching the file system. | The static-file path check rejects NUL bytes. |
| The asset cache reaches 5 MB | New files still serve, but later requests read them without adding them to the memory cache. | The cache size limit stops further cache growth. |
| A playback request supplies an invalid host | The request is rejected instead of becoming an open proxy to an unrelated host. | The playback route accepts only Google video or YouTube host names. |
| A route raises an error outside the API exclusions | The server returns the configured localized HTML error page with issue details. | The 500 error handler and HTML error template handle the exception. |
Key files
| File | Why to read it |
|---|---|
src/invidious.cr | Shows where request setup, routes, error handlers, middleware, and static asset delivery join the server bootstrap. |
src/invidious/routes/before_all.cr | Defines the shared request context and browser response policy. |
src/invidious/helpers/handlers.cr | Defines path-scoped authentication, API, frame, compression, and error behavior. |
src/invidious/http_server/static_assets_handler.cr | Defines the current asset delivery model, cache policy, MIME handling, and range support. |
src/ext/kemal_static_file_handler.cr | Shows the framework compatibility path for static files and the older asset cache behavior. |
src/invidious/helpers/errors.cr | Defines the HTML, Atom, JSON, and redirect error response shapes. |
src/invidious/routes/errors.cr | Defines recovery and redirect behavior for unknown short paths. |
src/invidious/http_server/utils.cr | Defines shared proxy URL and query parameter transformations. |
src/invidious/helpers/utils.cr | Defines public-host, safe-return-path, and byte-range helpers used by request and playback routes. |
src/invidious/routes/api/manifest.cr | Shows how manifest responses preserve media content types and turn upstream media URLs into local proxy URLs. |
src/invidious/routes/video_playback.cr | Shows how the shared proxy URL and range contracts deliver media without exposing arbitrary hosts. |
src/invidious/routes/watch.cr | Shows how a web route consumes shared preferences, user state, and proxy URLs before rendering or redirecting. |
src/invidious/routes/api/v1/authenticated.cr, src/invidious/routes/api/v1/channels.cr, src/invidious/routes/api/v1/feeds.cr, src/invidious/routes/api/v1/videos.cr | Show the API-side contracts for shared preferences, authentication, JSON content types, and route-level errors. |