Plugin & Configuration Reference¶
API reference for VitePlugin, ViteConfig, and all configuration dataclasses in litestar_vite.config.
Core Plugin & Root Config¶
VitePlugin
¶
Bases: InitPlugin, CLIPlugin
Vite plugin for Litestar.
This plugin integrates Vite with Litestar, providing:
- Static file serving configuration
- Jinja2 template callables for asset tags
- Vite dev server process management
- Async asset loader initialization
Example
Attributes:
| Name | Type | Description |
|---|---|---|
proxy_client | httpx2.AsyncClient | None | Return the pooled development HTTP proxy client, if initialized. |
config | ViteConfig | Get the Vite configuration. |
asset_loader | ViteAssetLoader | Get the asset loader instance. |
fragment_engine | FragmentEngine | Return the active FragmentEngine instance, initializing if needed. |
spa_handler | AppHandler | None | Return the configured SPA handler when SPA mode is enabled. |
get_ipc_transport
¶
Resolve the IPC transport for the active runtime mode.
In development mode, returns an HTTP/1.1 TCP transport targeting the
active Vite dev server's /__litestar_ssr__ endpoint. In production
mode, returns a cached StdioIPCTransport targeting the built SSR worker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ssr_config
|
InertiaSSRConfig | None
|
Configuration supplied by a separately registered InertiaPlugin. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Configured BaseIPCTransport instance. |
render_fragment
¶
Render a UI component fragment to HTML asynchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
component
|
str
|
Component path or name. |
required |
props
|
dict[str, Any] | None
|
Optional properties dictionary passed to the component. |
None
|
mode
|
Literal['static', 'island']
|
Render mode, either 'static' (pure HTML) or 'island' (with client hydration). |
'static'
|
Returns:
| Type | Description |
|---|---|
str
|
Rendered HTML string with prepended scoped CSS. |
render_fragment_sync
¶
Render a UI component fragment to HTML synchronously.
Useful for synchronous Jinja2 template rendering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
component
|
str
|
Component path or name. |
required |
props
|
dict[str, Any] | None
|
Optional properties dictionary passed to the component. |
None
|
mode
|
Literal['static', 'island']
|
Render mode, either 'static' (pure HTML) or 'island' (with client hydration). |
'static'
|
Returns:
| Type | Description |
|---|---|
str
|
Rendered HTML string with prepended scoped CSS. |
get_static_server_config
¶
Describe where the production static bundle should be served from.
Returns:
| Type | Description |
|---|---|
StaticServerConfig
|
A |
StaticServerConfig
|
the production bundle is eligible for direct web-server serving, or |
StaticServerConfig
|
a diagnostic |
on_cli_init
¶
Register CLI commands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cli
|
Group
|
The Click command group to add commands to. |
required |
on_app_init
¶
Configure the Litestar application for Vite.
This method wires up supporting configuration for dev/prod operation:
- Adds types used by generated handlers to the signature namespace.
- Ensures a consistent NotFound handler for asset/proxy lookups.
- Registers optional Inertia and Jinja integrations.
- Configures static file routing when enabled.
- Configures dev proxy middleware based on proxy_mode.
- Creates/initializes the SPA handler where applicable and registers lifespans.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app_config
|
AppConfig
|
The Litestar application configuration. |
required |
Returns:
| Type | Description |
|---|---|
AppConfig
|
The modified application configuration. |
get_route_prefixes
¶
Return the immutable route-prefix cache owned by this plugin.
server_lifespan
¶
Server-level lifespan context manager (runs ONCE per server, before workers).
This is called by Litestar CLI before workers start. It handles: - Environment variable setup (with logging) - Vite dev server process start/stop (ONE instance for all workers) - Type export on startup
Note: SPA handler and asset loader initialization happens in the per-worker
lifespan method, which is auto-registered in on_app_init.
Hotfile behavior: the JS plugin's listening callback writes the authoritative target once the Vite socket is ready. Python pre-writes only user-asserted external targets whose dev servers do not run the JS plugin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app
|
Litestar
|
The Litestar application instance. |
required |
Yields:
| Type | Description |
|---|---|
None
|
None |
lifespan
¶
Worker-level lifespan context manager (runs per worker process).
This is auto-registered in on_app_init and handles per-worker initialization:
- Environment variable setup (silently - each worker needs process-local env vars)
- Asset loader initialization
- SPA handler initialization
- Route metadata injection
Note: The Vite dev server process is started in server_lifespan, which
runs ONCE per server before workers start.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app
|
Litestar
|
The Litestar application instance. |
required |
Yields:
| Type | Description |
|---|---|
AsyncGenerator[None, None]
|
None |
ViteConfig
¶
Root configuration combining operating mode, paths, runtime, Inertia, SPA, typegen, and deployment settings.
Attributes:
| Name | Type | Description |
|---|---|---|
mode | Literal['spa', 'template', 'htmx', 'hybrid', 'inertia', 'framework', 'ssr', 'ssg', 'external'] | None | Serving mode ( |
paths | PathConfig | Filesystem and URL path configuration ( |
runtime | RuntimeConfig | Runtime execution, single-port proxy, and JS executor configuration. |
types | TypeGenConfig | bool | None | Type generation configuration ( |
inertia | InertiaConfig | bool | None | Inertia.js v2 configuration ( |
spa | SPAConfig | bool | None | SPA HTML transformation settings ( |
logging | LoggingConfig | bool | None | Console output and banner logging settings ( |
dev_mode | bool | Shortcut flag that sets |
base_url | str | None | Base URL prefix for the application entrypoint ( |
deploy | DeployConfig | bool | CDN deployment configuration ( |
enabled | bool | None | Whether |
static_props | dict[str, Any] | Public build-time dictionary written to |
guards | Sequence[Guard] | None | Litestar route guards applied to the |
exclude_static_from_auth | bool | Set |
spa_path | str | None | Route path where |
include_root_spa_paths | bool | Also register root |
executor | JSExecutor | Get the JavaScript executor instance. |
bundle_dir | Path | Get bundle directory path. |
resource_dir | Path | Get resource directory path. |
static_dir | Path | Get static directory path. |
root_dir | Path | Get root directory path. |
manifest_name | str | Get manifest file name. |
hot_file | str | Get hot file name. |
asset_url | str | Get asset URL. |
host | str | Get dev server host. |
port | int | Get dev server port. |
protocol | str | Get dev server protocol. |
hot_reload | bool | Check if hot reload is enabled (derived from dev_mode and proxy_mode). |
is_dev_mode | bool | Check if dev mode is enabled. |
is_react | bool | Check if React mode is enabled. |
run_command | list[str] | Get the run command. |
build_command | list[str] | Get the build command. |
build_watch_command | list[str] | Get the watch command for building frontend in watch mode. |
serve_command | list[str] | None | Get the serve command for running production server. |
install_command | list[str] | Get the install command. |
health_check | bool | Check if health check is enabled. |
set_environment | bool | Check if environment should be set. |
set_static_folders | bool | Check if static folders should be configured. |
detect_nodeenv | bool | Check if nodeenv detection is enabled. |
proxy_mode | Literal['vite', 'proxy'] | None | Get proxy mode. |
external_dev_server | ExternalDevServer | None | Get external dev server config. |
spa_handler | bool | Check if SPA handler auto-registration is enabled. |
serves_own_html | bool | True when Litestar (not an external dev server) serves HTML for this app. |
registers_html_catchall | bool | True when the SPA handler should register a |
wants_inertia_html_shell | bool | True when Inertia uses |
wants_html_proxy | bool | True when an external dev server owns HTML and Litestar proxies to it. |
inertia_compatible | bool | True when this mode supports Inertia.js integration. |
wants_spa_config | bool | True when |
http2 | bool | Check if HTTP/2 is enabled for proxy connections. |
csp_nonce | str | None | Return the CSP nonce used for injected inline scripts. |
link_preload_headers | bool | Return whether RFC 8288 Link preload headers are emitted in production. |
early_hints | bool | Return whether ASGI 103 Early Hints frames are emitted in production. |
immutable_cache_headers | bool | Return whether content-hashed static assets receive immutable Cache-Control headers. |
ssr_transport | Literal['stdio', 'wasm', 'auto'] | Return the configured production SSR transport mode. |
ssr_enabled | bool | Return whether Server-Side Rendering (Inertia SSR or custom SSR output) is enabled. |
trusted_proxies | list[str] | str | None | Get trusted proxies configuration. |
ssr_output_dir | Path | None | Get SSR output directory. |
spa_config | SPAConfig | None | Get SPA configuration if enabled, or None if disabled. |
deploy_config | DeployConfig | None | Get deploy configuration if enabled. |
logging_config | LoggingConfig | Get logging configuration. |
validate_mode
¶
Validate the mode configuration against the project structure.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the configuration is invalid for the selected mode. |
reset_executor
¶
Reset the cached executor instance.
Call this after modifying logging config to pick up new settings.
candidate_index_html_paths
¶
Return possible index.html locations for SPA mode detection.
Order mirrors the JS plugin auto-detection: 1. bundle_dir/index.html (for production static builds like Astro/Nuxt/SvelteKit) 2. resource_dir/index.html 3. root_dir/index.html 4. static_dir/index.html
Returns:
| Type | Description |
|---|---|
list[Path]
|
A de-duplicated list of candidate index.html paths, ordered by preference. |
candidate_manifest_paths
¶
Return possible manifest.json locations in the bundle directory.
Some meta-frameworks emit the manifest under a .vite/ subdirectory
(e.g. <bundle_dir>/.vite/manifest.json), while plain Vite builds may
write it directly to <bundle_dir>/manifest.json.
Returns:
| Type | Description |
|---|---|
list[Path]
|
A de-duplicated list of candidate manifest paths, ordered by preference. |
resolve_manifest_path
¶
Resolve the most likely manifest path.
Returns:
| Type | Description |
|---|---|
Path
|
The first existing manifest path, or the highest-priority candidate when none exist. |
has_built_assets
¶
Check if production assets exist in the bundle directory.
Returns:
| Type | Description |
|---|---|
bool
|
True if a manifest or built index.html exists in bundle_dir. |
Note
This method checks the bundle_dir (output directory) for built artifacts, NOT source directories. The presence of source index.html in resource_dir does not indicate built assets exist.
create_plugin
¶
Create a VitePlugin instance from this configuration.
Conforms to Litestar's InitPluginProtocol for config-based plugin instantiation.
Returns:
| Type | Description |
|---|---|
VitePlugin
|
Configured VitePlugin instance. |
Filesystem & Runtime Configuration¶
PathConfig
¶
File system and URL path configuration for Vite source, public, and bundle directories.
Attributes:
| Name | Type | Description |
|---|---|---|
root | str | Path | Root directory of the frontend project, defaulting to the current working directory. |
bundle_dir | str | Path | Output directory for compiled production bundles and |
resource_dir | str | Path | TypeScript/JavaScript source directory containing entrypoints and components. |
static_dir | str | Path | Static public assets directory served as-is by Vite ( |
manifest_name | str | Filename of the Vite build manifest inside |
hot_file | str | Filename inside |
asset_url | str | Base URL prefix prepended to static and built asset references. |
ssr_output_dir | str | Path | None | Optional output directory for compiled server-side rendering (SSR) bundles. |
RuntimeConfig
¶
Runtime process management, dev proxy, and JavaScript executor settings.
Attributes:
| Name | Type | Description |
|---|---|---|
dev_mode | bool | Enable development mode with Vite HMR and watch processes. |
proxy_mode | Literal['vite', 'proxy'] | None | Dev proxy routing mode ( |
external_dev_server | ExternalDevServer | str | None | External dev server configuration or target URL string used when |
host | str | Hostname or IP address where the Vite dev server binds. |
port | int | TCP port where the Vite dev server listens. |
protocol | Literal['http', 'https'] | Protocol ( |
executor | Literal['node', 'bun', 'deno', 'yarn', 'pnpm'] | None | JavaScript runtime/package manager used to execute Vite commands ( |
run_command | list[str] | None | Custom command argv to start the Vite dev server (auto-derived from |
build_command | list[str] | None | Custom command argv to run a production Vite build (auto-derived from |
build_watch_command | list[str] | None | Custom command argv to run Vite in watch-build mode (auto-derived from |
serve_command | list[str] | None | Custom command argv to run the production SSR server (auto-derived from |
install_command | list[str] | None | Custom command argv to install frontend dependencies (auto-derived from |
is_react | bool | Inject the |
health_check | bool | Poll the Vite dev server for readiness before completing startup. |
detect_nodeenv | bool | Detect and run |
provisioning_mode | Literal['auto', 'wheel', 'nodeenv', 'system'] | How runtime binaries are located ( |
ssr_transport | Literal['stdio', 'wasm', 'auto'] | Production SSR IPC transport selection ( |
set_environment | bool | Export resolved Vite settings ( |
set_static_folders | bool | Automatically mount static asset directories on the Litestar router. |
csp_nonce | str | None | Content Security Policy nonce applied to injected inline |
link_preload_headers | bool | Emit RFC 8288 |
early_hints | bool | Emit a |
immutable_cache_headers | bool | Attach |
spa_handler | bool | Automatically register the |
http2 | bool | Enable HTTP/2 multiplexing for proxy HTTP requests. |
start_dev_server | bool | Automatically spawn and manage the Vite dev server subprocess during Litestar lifespan. |
trusted_proxies | list[str] | str | None | Trusted proxy hosts/CIDRs ( |
extra_route_prefixes | tuple[str, ...] | Additional backend route prefixes excluded from dev proxy forwarding and SPA catch-all routing. |
has_explicit_executor | bool | Return whether the runtime executor was explicitly configured via args or env. |
apply_detected_executor
¶
Apply a lockfile-detected executor and refresh non-explicit command lists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
executor
|
ExecutorType
|
The detected executor identifier. |
required |
ExternalDevServer
¶
Configuration for proxying to an external (non-Vite) development server.
Attributes:
| Name | Type | Description |
|---|---|---|
target | str | None | Target URL of the external dev server (for example, |
command | list[str] | None | Custom command argv used to start the external dev server. |
build_command | list[str] | None | Custom command argv used to build production assets for the external framework. |
http2 | bool | Enable HTTP/2 for proxy connections to the external dev server. |
enabled | bool | Whether the external dev server proxy is enabled. |
SPAConfig
¶
Configuration for SPA HTML transformations and CSRF token injection.
Attributes:
| Name | Type | Description |
|---|---|---|
inject_csrf | bool | Whether to inject the Litestar CSRF token into the HTML document. |
csrf_var_name | str | Global |
app_selector | str | CSS selector for the application root element receiving data attributes. |
cache_transformed_html | bool | Cache transformed HTML in production when per-request |
cache_duration | int | HTTP |
LoggingConfig
¶
Logging configuration for Python and TypeScript console output.
Attributes:
| Name | Type | Description |
|---|---|---|
level | Literal['quiet', 'normal', 'verbose'] | Console verbosity level ( |
show_paths_absolute | bool | Display absolute filesystem paths instead of workspace-relative paths in log output. |
suppress_npm_output | bool | Suppress package-manager script echo lines ( |
suppress_vite_banner | bool | Suppress the Vite startup banner so only the Litestar startup banner is shown. |
timestamps | bool | Include timestamps in console log messages. |
detect_runtime
¶
Detect the JavaScript runtime/package manager from project lockfiles and manifests.
Delegates to detect_runtime_marker and falls back to "node".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root_dir
|
Path
|
Project root directory to inspect. |
required |
Returns:
| Type | Description |
|---|---|
ExecutorType
|
The detected executor identifier. |
detect_runtime_marker
¶
Return the executor implied by project lockfiles or manifests together with its source.
Precedence
bun.lockborbun.lock->"bun"deno.lock,deno.json, ordeno.jsonc->"deno"pnpm-lock.yaml->"pnpm"yarn.lock->"yarn"package-lock.json->"node"package.json"packageManager"field (pnpm@...,yarn@...,bun@...,deno@...)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root_dir
|
Path
|
Project root directory to inspect. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ExecutorType, str] | None
|
|
tuple[ExecutorType, str] | None
|
|
tuple[ExecutorType, str] | None
|
when no marker is present. |
Inertia, TypeGen & Deploy Configuration¶
InertiaConfig
¶
Configuration for Inertia.js v2 protocol handling, shared props, SSR, and Precognition.
Attributes:
| Name | Type | Description |
|---|---|---|
root_template | str | Root HTML or Jinja template filename used for initial Inertia page responses. |
component_opt_keys | tuple[str, ...] | Route handler |
redirect_unauthorized_to | str | None | Optional URL path to redirect unauthenticated ( |
redirect_404 | str | None | Optional URL path to redirect |
extra_static_page_props | dict[str, Any] | Static key-value props automatically merged into every Inertia page response. |
extra_session_page_props | set[str] | dict[str, type] | Session key names (or mapping of session keys to Python types) copied into page props when a session exists. |
shared_page_prop_types | dict[str, Any] | None | Type-only mapping of |
encrypt_history | bool | Set |
type_gen | InertiaTypeGenConfig | None | Type generation options controlling default |
ssr | InertiaSSRConfig | bool | None | Enable Inertia SSR ( |
use_script_element | bool | Embed initial page JSON in |
precognition | bool | Register the Laravel Precognition validation exception handler for |
ssr_config | InertiaSSRConfig | None | Return the SSR config when enabled, otherwise None. |
InertiaSSRConfig
¶
Server-side rendering (SSR) and circuit breaker settings for Inertia.js.
Attributes:
| Name | Type | Description |
|---|---|---|
enabled | bool | Whether server-side rendering is active for Inertia full-page HTML responses. |
timeout | float | Maximum time in seconds to wait for an SSR render call before timing out. |
target_selector | str | CSS selector of the element replaced by SSR HTML in |
command | list[str] | None | Command argv to launch the production stdio SSR worker ( |
cwd | Path | None | Working directory for the production SSR subprocess ( |
fallback_to_client | bool | Fall back gracefully to client-side rendering when SSR fails or times out. |
circuit_breaker_enabled | bool | Enable the in-memory |
circuit_breaker_failure_threshold | int | Consecutive SSR failures required before the circuit breaker trips to |
circuit_breaker_reset_timeout | float | Cooldown window in seconds before a tripped circuit breaker transitions to |
InertiaTypeGenConfig
¶
Type generation options for default Inertia interfaces in page-props.ts.
Attributes:
| Name | Type | Description |
|---|---|---|
include_default_auth | bool | Emit default |
include_default_flash | bool | Emit the default |
TypeGenConfig
¶
Configuration for OpenAPI, AsyncAPI, route, and Inertia page-props TypeScript code generation.
Attributes:
| Name | Type | Description |
|---|---|---|
output | Path | Output directory for generated schemas and TypeScript files. |
openapi_path | Path | None | Path to export the deterministic |
routes_path | Path | None | Path to export route metadata JSON ( |
routes_ts_path | Path | None | Path to export the generated |
asyncapi_path | Path | None | Path to export the normalized |
generate_zod | bool | Generate Zod validation schemas alongside OpenAPI TypeScript types. |
generate_sdk | bool | Generate the |
generate_routes | bool | Generate the typed Ziggy-style |
generate_page_props | bool | Generate |
generate_channels | bool | Generate |
channels_ts_path | Path | None | Path to export the generated |
generate_schemas | bool | Generate |
schemas_ts_path | Path | None | Path to export the generated |
global_route | bool | Register the generated |
fail_on_error | bool | None | Fail the Vite command when type generation errors occur ( |
fallback_type | Literal['unknown', 'any'] | Fallback TypeScript value type ( |
type_import_paths | dict[str, str] | Map of schema/type names to custom TypeScript import paths for types excluded from OpenAPI. |
page_props_path | Path | None | Path to export Inertia page metadata JSON ( |
extra_commands | Sequence[Sequence[str]] | Additional CLI commands ( |
DeployConfig
¶
CDN deployment configuration for uploading built Vite bundles via fsspec.
Attributes:
| Name | Type | Description |
|---|---|---|
enabled | bool | Enable CDN deployment features. |
storage_backend | str | None |
|
storage_options | dict[str, Any] | Provider options forwarded to |
asset_url | str | None | Public CDN URL prefix written to |
delete_orphaned | bool | Remove remote files not present in the local bundle during sync. |
include_manifest | bool | Upload |
content_types | dict[str, str] | Optional content-type overrides keyed by file extension. |
with_overrides
¶
Return a copy with overrides applied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
storage_backend
|
str | None
|
Override for the storage URL. |
None
|
storage_options
|
dict[str, Any] | None
|
Override for backend options. |
None
|
asset_url
|
str | None
|
Override for the public asset URL. |
None
|
delete_orphaned
|
bool | None
|
Override deletion behaviour. |
None
|
Returns:
| Type | Description |
|---|---|
DeployConfig
|
DeployConfig copy with updated fields. |
PaginationContainer
¶
Bases: Protocol
Protocol for pagination containers (OffsetPagination, ClassicPagination) unwrapped for Inertia scroll.
Attributes:
| Name | Type | Description |
|---|---|---|
items | Sequence[Any] | Paginated sequence of item records extracted for the response. |