Skip to content

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_html_entry(entry, *, production_path, absolute_dev_asset_urls=False)

Resolve an exact Vite HTML entry from development or production.

resolve_html_entry_sync

resolve_html_entry_sync(
    entry, *, production_path, absolute_dev_asset_urls=False
)

Synchronously resolve an exact Vite HTML entry.

initialize_loader

initialize_loader(config)

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

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

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_hmr_client(*, csp_nonce=None)

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_tag(path, scripts_attrs=None, *, csp_nonce=None)

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_static_asset(path)

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_ws_client_tags(*, csp_nonce=None)

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_hmr_tags(*, csp_nonce=None)

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_asset_tags(path, scripts_attrs=None, _visited=None, *, csp_nonce=None)

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

render_preload_headers(path=None, *, manifest=None)

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 isEntry=True (or all non-chunk manifest keys) are used.

None
manifest dict[str, Any] | None

Optional manifest dictionary override.

None

Returns:

Type Description
list[str]

List of RFC 8288 Link header values (empty in development mode or when no manifest is loaded).

render_hmr_client

render_hmr_client(context, /, *, csp_nonce=None)

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_tag(context, /, path, scripts_attrs=None, *, csp_nonce=None)

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_static_asset(context, /, path)

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_routes(
    context,
    /,
    *,
    only=None,
    exclude=None,
    include_components=False,
    csp_nonce=None,
)

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_initializedbool

Whether the handler has been initialized.

inject_csrfbool

Whether CSRF token injection is enabled on SPAConfig.

configViteConfig

Return the ViteConfig associated with this handler.

initialize_async

initialize_async(vite_url=None, manifest=None)

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_sync(vite_url=None)

Initialize the handler synchronously.

Parameters:

Name Type Description Default
vite_url str | None

Optional Vite server URL to use for proxying.

None

shutdown_async

shutdown_async()

Shutdown the handler asynchronously.

get_preload_headers

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_html(request, *, page_data=None)

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_html_sync(*, page_data=None, csrf_token=None)

Get the HTML for the SPA synchronously.

Parameters:

Name Type Description Default
page_data dict[str, Any] | None

Optional page data to inject (e.g., Inertia page props).

None
csrf_token str | None

Optional CSRF token to inject.

None

Returns:

Type Description
str

The rendered HTML.

get_bytes

get_bytes(request=None)

Get cached or transformed index.html bytes (production).

Parameters:

Name Type Description Default
request Request[Any, Any, Any] | None

Optional incoming request for per-request CSRF token injection.

None

Returns:

Type Description
bytes

Cached or transformed HTML bytes.

create_route_handler

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

Bases: str, Enum

Where static files are served from.

Subclassing str is deliberate: consumers compare structurally against the literal value (config.placement == "native") without importing this package.

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
placementStaticPlacement

Static serving tier (StaticPlacement.NATIVE for Granian Rust or StaticPlacement.ASGI for Litestar).

mountstuple[StaticServerMount, ...]

Ordered tuple of static directory mounts.

reasonstr | None

Diagnostic explanation when placement falls back to StaticPlacement.ASGI.

StaticServerMount

Describe one static directory exposed to a native server.

Attributes:

Name Type Description
routestr

URL prefix mounted by the static file server (for example, '/static').

directoryPath

Resolved filesystem directory containing static assets.

directory_indexstr | None

Optional index filename (such as 'index.html') served for directory requests.

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_requestAfterRequestHookHandler | None

Optional Litestar after_request hook handler applied to static asset responses.

after_responseAfterResponseHookHandler | None

Optional Litestar after_response hook handler applied to static asset requests.

before_requestBeforeRequestHookHandler | None

Optional Litestar before_request hook handler executed before static file lookup.

cache_controlCacheControlHeader | None

Default Cache-Control header configuration for the static files router.

exception_handlersExceptionHandlersMap | None

Custom exception handlers registered on the static files router.

guardslist[Guard] | None

Route guards applied to static asset requests.

middlewareSequence[Middleware] | None

ASGI middleware sequence applied to the static files router.

optdict[str, Any] | None

Route opt metadata dictionary merged onto the static files router.

securitySequence[SecurityRequirement] | None

OpenAPI security requirements attached to the static files router.

tagsSequence[str] | None

OpenAPI tags attached to the static files router.

as_router_kwargs
as_router_kwargs()

Return the explicitly-set fields as create_static_files_router keyword arguments.

opt is excluded because the plugin merges it with its own options. Unset fields are omitted so Litestar's defaults apply.

Returns:

Type Description
dict[str, Any]

Keyword arguments for create_static_files_router.

asgi_override_fields
asgi_override_fields()

Return the list of configured fields that require ASGI request/response serving.

Empty containers count as unset: they configure no runtime behavior.

Returns:

Type Description
list[str]

Names of set non-metadata fields that modify runtime ASGI behavior.

has_asgi_overrides
has_asgi_overrides()

Return True if any configured field alters runtime ASGI request/response behavior.

Returns:

Type Description
bool

True if any ASGI-dependent field is set, False if the configuration is pure metadata.


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_namestr
silent_flagstr
Default: '--silent'
provisioning_modeProvisioningMode
Default: provisioning_mode
start_commandlist[str]

Get the default command to start the dev server (e.g., npm run start).

build_commandlist[str]

Get the default command to build for production (e.g., npm run build).

install

install(cwd)

Install dependencies.

update

update(cwd, *, latest=False)

Update dependencies.

Parameters:

Name Type Description Default
cwd Path

The working directory.

required
latest bool

If True, update to latest versions (ignoring semver constraints where supported).

False

run

run(args, cwd)

Run a command.

Returns:

Type Description
Popen[Any]

The result.

execute

execute(args, cwd)

Execute a command and wait for it to finish.

which

which(bin_name, provisioning_mode='auto')

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 JSExecutor).

'auto'

Returns:

Type Description
str | None

Resolved executable path string if found, otherwise None.

ssr_command

ssr_command(entry_point)

Return the command list to run a production SSR bundle.

Parameters:

Name Type Description Default
entry_point Path

Path to the built SSR bundle file.

required

Returns:

Type Description
list[str]

Command list suitable for StdioIPCTransport.

NodeExecutor

Bases: CommandExecutor

Node.js executor.

Attributes:

Name Type Description
update_latest_flagstr
Default: '--save'

BunExecutor

Bases: CommandExecutor

Bun executor.

ssr_command
ssr_command(entry_point)

Return the Bun command list to run a production SSR bundle.

DenoExecutor

Bases: CommandExecutor

Deno executor.

Attributes:

Name Type Description
silent_flagstr
Default: ''
update_latest_flagstr
Default: '--latest'
start_commandlist[str]

Get the default command to start the dev server using Deno tasks.

build_commandlist[str]

Get the default command to build for production using Deno tasks.

ssr_command
ssr_command(entry_point)

Return the Deno command list to run a production SSR bundle.

update
update(cwd, *, latest=False)

Update dependencies via deno outdated --update [--latest].

execute
execute(args, cwd)

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_commandstr
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_commandlist[str]

Get the default command to start the dev server using nodeenv npm.

build_commandlist[str]

Get the default command to build for production using nodeenv npm.

install_nodeenv
install_nodeenv(cwd)

Install nodeenv when available in the environment.

install
install(cwd)

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.

update
update(cwd, *, latest=False)

Run npm update inside the active nodeenv virtual environment.

run
run(args, cwd)

Start a long-running npm subprocess inside the nodeenv environment.

execute
execute(args, cwd)

Execute an npm command synchronously inside the nodeenv environment.

resolve_ssr_command

resolve_ssr_command(config=None, ssr_config=None)

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 ViteConfig instance.

None
ssr_config InertiaSSRConfig | None

Optional resolved InertiaSSRConfig instance.

None

Returns:

Type Description
list[str]

Command list suitable for StdioIPCTransport.


Exceptions Hierarchy

LitestarViteError

Bases: Exception

Base exception for Litestar-Vite related errors.

ManifestNotFoundError

Bases: LitestarViteError

Raised when the manifest file is not found.

AssetNotFoundError

Bases: LitestarViteError

Raised when an asset is not found in the manifest.

HTMLEntryResolutionError

Bases: LitestarViteError

Raised when a Vite HTML entry cannot be resolved.

MissingDependencyError

Bases: LitestarViteError, ImportError

Raised when a package is not installed but required.

ViteExecutableNotFoundError

Bases: LitestarViteError

Raised when the vite executable is not found.

ViteExecutionError

Bases: LitestarViteError

Raised when the vite execution fails.

ViteProcessError

Bases: LitestarViteError

Raised when the Vite process fails to start or stop.


HTML Transform Helpers

inject_head_html

inject_head_html(html, content)

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 </head> when present.

str

Falls back to injecting before </html> or appending at the end.

inject_head_script

inject_head_script(html, script, *, escape=True, nonce=None)

Inject a script tag before the closing tag.

Parameters:

Name Type Description Default
html str

The HTML document.

required
script str

The JavaScript code to inject (without ' result = transform_asset_urls(html, manifest)