Runtime, Assets & Exceptions Reference¶
API reference for ViteAssetLoader, Jinja template helpers, AppHandler, ViteProxyMiddleware, Granian native static serving contracts, JavaScript runtime executors, and litestar_vite.exceptions.
Asset Loader & Template Callables¶
ViteAssetLoader
¶
Vite asset loader for managing frontend assets.
This class handles loading and rendering of Vite-managed assets. It supports both development mode (with HMR) and production mode (with manifest-based asset resolution).
The loader is designed to be instantiated per-app (not a singleton) and supports async initialization for non-blocking file I/O.
Attributes:
| Name | Type | Description |
|---|---|---|
config | The Vite configuration. |
Example
loader = ViteAssetLoader(config) await loader.initialize() html = loader.render_asset_tag("src/main.ts")
resolve_html_entry
¶
Resolve an exact Vite HTML entry from development or production.
resolve_html_entry_sync
¶
Synchronously resolve an exact Vite HTML entry.
initialize_loader
¶
Synchronously initialize a loader instance.
This is a convenience method for synchronous initialization.
For async contexts, prefer using initialize() after construction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ViteConfig
|
The Vite configuration. |
required |
Returns:
| Type | Description |
|---|---|
ViteAssetLoader
|
An initialized ViteAssetLoader instance. |
initialize
¶
Asynchronously initialize the loader.
This method performs async file I/O to load the manifest or hot file. Call this during app startup in an async context.
parse_manifest
¶
Synchronously parse the Vite manifest file.
This method reads the manifest.json file in production mode or the hot file in development mode.
Note: For async contexts, use initialize() instead.
render_hmr_client
¶
Render the HMR client script tags.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
csp_nonce
|
str | None
|
Optional per-request Content Security Policy nonce override. |
None
|
Returns:
| Type | Description |
|---|---|
Markup
|
HTML markup containing React HMR and Vite client script tags. |
render_asset_tag
¶
Render asset tags for the specified path(s).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | list[str]
|
Single path or list of paths to assets. |
required |
scripts_attrs
|
dict[str, str] | None
|
Optional attributes for script tags. |
None
|
csp_nonce
|
str | None
|
Optional per-request Content Security Policy nonce override. |
None
|
Returns:
| Type | Description |
|---|---|
Markup
|
HTML markup for script and link tags. |
get_static_asset
¶
Get the URL for a static asset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The path to the asset. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The full URL to the asset. |
Raises:
| Type | Description |
|---|---|
AssetNotFoundError
|
If the asset is not in the manifest. |
generate_ws_client_tags
¶
Generate the Vite HMR client script tag.
Only generates output in development mode with hot reload enabled.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
csp_nonce
|
str | None
|
Optional per-request Content Security Policy nonce override. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Script tag HTML or empty string in production. |
generate_react_hmr_tags
¶
Generate React Fast Refresh preamble script.
Only generates output when React mode is enabled in development.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
csp_nonce
|
str | None
|
Optional per-request Content Security Policy nonce override. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
React refresh script HTML or empty string. |
generate_asset_tags
¶
Generate all asset tags for the specified file(s).
Follows the official Vite Backend Integration specification:
1. Emits <link rel="stylesheet"> tags for entry and transitive imported CSS.
2. Emits <script type="module"> tags (without default async) for entry scripts.
3. Emits <link rel="modulepreload" crossorigin> tags for transitive imported chunks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | list[str]
|
Path or list of paths to assets. |
required |
scripts_attrs
|
dict[str, str] | None
|
Optional attributes for script tags. |
None
|
_visited
|
set[str] | None
|
Optional set of already visited paths for cycle prevention. |
None
|
csp_nonce
|
str | None
|
Optional per-request Content Security Policy nonce override. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
HTML string with all necessary script and link tags. |
Raises:
| Type | Description |
|---|---|
ImproperlyConfiguredException
|
If asset not found in manifest. |
render_preload_headers
¶
Generate RFC 8288 HTTP Link header values for preloading entry scripts, chunks, and stylesheets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | list[str] | None
|
Optional manifest entry key or list of keys. When omitted, all manifest
entries marked with |
None
|
manifest
|
dict[str, Any] | None
|
Optional manifest dictionary override. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
List of RFC 8288 |
render_hmr_client
¶
Render the HMR client script tag.
This is a Jinja2 template callable that renders the Vite HMR client script tag for development mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
Mapping[str, Any]
|
The template context containing the request. |
required |
csp_nonce
|
str | None
|
Optional per-request Content Security Policy nonce override. |
None
|
Returns:
| Type | Description |
|---|---|
Markup
|
HTML markup for the HMR client script, or empty markup if |
Markup
|
VitePlugin is not registered. |
render_asset_tag
¶
Render asset tags for the specified path(s).
This is a Jinja2 template callable that renders script/link tags for Vite-managed assets. Also works for HTMX partial responses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
Mapping[str, Any]
|
The template context containing the request. |
required |
path
|
str | list[str]
|
Single path or list of paths to assets. |
required |
scripts_attrs
|
dict[str, str] | None
|
Optional attributes for script tags. |
None
|
csp_nonce
|
str | None
|
Optional per-request Content Security Policy nonce override. |
None
|
Returns:
| Type | Description |
|---|---|
Markup
|
HTML markup for the asset tags, or empty markup if VitePlugin |
Markup
|
is not registered. |
Example
In a Jinja2 template: {{ vite_asset("src/main.ts") }} {{ vite_asset("src/components/UserProfile.tsx") }}
render_static_asset
¶
Render a static asset URL.
This is a Jinja2 template callable that returns the URL for a static asset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
Mapping[str, Any]
|
The template context containing the request. |
required |
path
|
str
|
Path to the static asset. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The full URL to the static asset, or empty string if VitePlugin |
str
|
is not registered. |
render_routes
¶
Render inline script tag with route definitions.
This is a Jinja2 template callable that renders an inline script tag containing route metadata for client-side type-safe routing.
The script defines a global window.Litestar.routes object that can be
used by frontend routers.
Uses Litestar's built-in serializers, picking up any custom type encoders configured on the app.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
Mapping[str, Any]
|
The template context containing the request. |
required |
only
|
list[str] | None
|
Optional list of route patterns to include. |
None
|
exclude
|
list[str] | None
|
Optional list of route patterns to exclude. |
None
|
include_components
|
bool
|
Include Inertia component names. |
False
|
csp_nonce
|
str | None
|
Optional per-request Content Security Policy nonce override. |
None
|
Returns:
| Type | Description |
|---|---|
Markup
|
HTML markup for the inline routes script containing route metadata |
Markup
|
as a JSON object. |
Example
In a Jinja2 template: {{ vite_routes() }} {{ vite_routes(exclude=['/api/internal']) }}
SPA Handler & Single-Port Dev Proxy¶
AppHandler
¶
Handler for serving SPA HTML in both dev and production modes.
Attributes:
| Name | Type | Description |
|---|---|---|
is_initialized | bool | Whether the handler has been initialized. |
inject_csrf | bool | Whether CSRF token injection is enabled on SPAConfig. |
config | ViteConfig | Return the ViteConfig associated with this handler. |
initialize_async
¶
Initialize the handler asynchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vite_url
|
str | None
|
Optional Vite server URL to use for proxying. |
None
|
manifest
|
dict[str, Any] | None
|
Optional pre-parsed manifest from the shared asset loader. This avoids reading and parsing the same file again during worker startup. It is ignored when hot development or an external development server skips manifest loading. |
None
|
initialize_sync
¶
Initialize the handler synchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vite_url
|
str | None
|
Optional Vite server URL to use for proxying. |
None
|
get_preload_headers
¶
Return RFC 8288 Link preload header values for the served HTML entry.
The list is computed once from the manifest and cached for the lifetime
of the handler. When the manifest contains an entry for the served
index.html only that entry's graph is preloaded; otherwise every
isEntry chunk is used. Returns an empty list in development mode or
when both link_preload_headers and early_hints are disabled.
get_html
¶
Get the HTML for the SPA with optional transformations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request[Any, Any, Any]
|
Incoming request. |
required |
page_data
|
dict[str, Any] | None
|
Optional page data to inject (e.g., Inertia page props). |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The rendered HTML. |
Raises:
| Type | Description |
|---|---|
ImproperlyConfiguredException
|
If the handler is not initialized. |
get_html_sync
¶
get_bytes
¶
create_route_handler
¶
Create a Litestar route handler for the SPA.
Returns:
| Type | Description |
|---|---|
HTTPRouteHandler
|
A Litestar route handler suitable for registering on an application. |
ViteProxyMiddleware
¶
Bases: AbstractMiddleware
ASGI middleware to proxy Vite dev HTTP traffic to internal Vite server.
HTTP requests use the HTTPX2 client with connection pooling and HTTP/2 support. WebSocket traffic (used by Vite HMR) is handled by a dedicated WebSocket route handler created by create_vite_hmr_handler().
The middleware reads the Vite server URL from the hotfile dynamically, ensuring it always connects to the correct Vite server even if the port changes.
Static File Serving & Granian Native Placement¶
StaticPlacement
¶
StaticServerConfig
¶
Describe where static files should be served from.
reason is diagnostic detail that is meaningful only when placement is
ASGI; it explains why Litestar's static router must serve (development mode,
framework/SSR routing, manifest/build-state problems, and similar).
Attributes:
| Name | Type | Description |
|---|---|---|
placement | StaticPlacement | Static serving tier ( |
mounts | tuple[StaticServerMount, ...] | Ordered tuple of static directory mounts. |
reason | str | None | Diagnostic explanation when |
StaticServerMount
¶
Describe one static directory exposed to a native server.
Attributes:
| Name | Type | Description |
|---|---|---|
route | str | URL prefix mounted by the static file server (for example, |
directory | Path | Resolved filesystem directory containing static assets. |
directory_index | str | None | Optional index filename (such as |
StaticFilesConfig
¶
Configuration for static file serving.
Field names must match keyword parameters of Litestar's create_static_files_router;
as_router_kwargs() forwards the set fields to it.
Attributes:
| Name | Type | Description |
|---|---|---|
after_request | AfterRequestHookHandler | None | Optional Litestar |
after_response | AfterResponseHookHandler | None | Optional Litestar |
before_request | BeforeRequestHookHandler | None | Optional Litestar |
cache_control | CacheControlHeader | None | Default |
exception_handlers | ExceptionHandlersMap | None | Custom exception handlers registered on the static files router. |
guards | list[Guard] | None | Route guards applied to static asset requests. |
middleware | Sequence[Middleware] | None | ASGI middleware sequence applied to the static files router. |
opt | dict[str, Any] | None | Route |
security | Sequence[SecurityRequirement] | None | OpenAPI security requirements attached to the static files router. |
tags | Sequence[str] | None | OpenAPI tags attached to the static files router. |
JavaScript Runtime Executors¶
JSExecutor
¶
Bases: ABC
Abstract base class for Javascript executors.
The default silent_flag matches npm-style CLIs (--silent). Executors that do not support a silent flag
(e.g., Deno) override it with an empty string.
Attributes:
| Name | Type | Description |
|---|---|---|
bin_name | str | |
silent_flag | str | Default: '--silent' |
provisioning_mode | ProvisioningMode | Default: provisioning_mode |
start_command | list[str] | Get the default command to start the dev server (e.g., npm run start). |
build_command | list[str] | Get the default command to build for production (e.g., npm run build). |
update
¶
which
¶
Locate an executable according to provisioning_mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bin_name
|
str
|
Bare binary name to resolve. |
required |
provisioning_mode
|
ProvisioningMode
|
Discovery policy (see |
'auto'
|
Returns:
| Type | Description |
|---|---|
str | None
|
Resolved executable path string if found, otherwise |
NodeExecutor
¶
Bases: CommandExecutor
Node.js executor.
Attributes:
| Name | Type | Description |
|---|---|---|
update_latest_flag | str | Default: '--save' |
BunExecutor
¶
Bases: CommandExecutor
Bun executor.
DenoExecutor
¶
Bases: CommandExecutor
Deno executor.
Attributes:
| Name | Type | Description |
|---|---|---|
silent_flag | str | Default: '' |
update_latest_flag | str | Default: '--latest' |
start_command | list[str] | Get the default command to start the dev server using Deno tasks. |
build_command | list[str] | Get the default command to build for production using Deno tasks. |
execute
¶
Execute a Deno command or script and wait for completion.
When args does not begin with a native Deno subcommand (such as
task or run), ["run", "-A"] is prepended before the script
or module arguments.
PnpmExecutor
¶
Bases: CommandExecutor
PNPM executor.
YarnExecutor
¶
Bases: CommandExecutor
Yarn executor.
Attributes:
| Name | Type | Description |
|---|---|---|
update_command | str | Default: 'upgrade' |
NodeenvExecutor
¶
Bases: JSExecutor
Nodeenv executor.
This executor detects and uses nodeenv in a Python virtual environment. It installs nodeenv if not present and uses the npm from within the virtualenv.
Attributes:
| Name | Type | Description |
|---|---|---|
start_command | list[str] | Get the default command to start the dev server using nodeenv npm. |
build_command | list[str] | Get the default command to build for production using nodeenv npm. |
install
¶
Run npm install within the nodeenv environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cwd
|
Path
|
The working directory for the installation. |
required |
Raises:
| Type | Description |
|---|---|
ViteExecutionError
|
If package installation exits with a non-zero status. |
resolve_ssr_command
¶
Resolve the production SSR worker command for the active JS runtime.
Honors an explicit ssr_config.command override first. Otherwise resolves the
built SSR bundle path and returns the runtime-appropriate invocation via the
configured executor (bun run <path>, deno run --allow-read --allow-env <path>,
or node <path>).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ViteConfig | None
|
Optional active |
None
|
ssr_config
|
InertiaSSRConfig | None
|
Optional resolved |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Command list suitable for |
Exceptions Hierarchy¶
ManifestNotFoundError
¶
AssetNotFoundError
¶
HTMLEntryResolutionError
¶
MissingDependencyError
¶
ViteExecutableNotFoundError
¶
ViteExecutionError
¶
ViteProcessError
¶
HTML Transform Helpers¶
inject_head_html
¶
Inject raw HTML into the <head> section.
This is used for Inertia SSR, where the SSR server returns an array of HTML strings
(typically <title>, <meta>, etc.) that must be placed in the final HTML response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
html
|
str
|
The HTML document. |
required |
content
|
str
|
Raw HTML to inject. This is inserted as-is. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The HTML with the content injected before |
str
|
Falls back to injecting before |