Skip to content

Fragments & SSR IPC Reference

API reference for UI component fragments (litestar_vite.fragments) and the Server-Side Rendering IPC transport and circuit breaker subsystem (litestar_vite.ipc).


UI Component Fragments & Islands

FragmentEngine

Orchestrates rendering UI component fragments over IPC transports.

get_component_css_urls

get_component_css_urls(component)

Extract all CSS file URLs for a component from manifest or dev server.

In production mode, looks up the component in the parsed manifest.json, collects its direct 'css' array, and recursively traverses 'imports' chunks to collect imported CSS dependencies with cycle detection. Normalizes paths using POSIX formatting to support Windows environments.

In development mode, returns the direct component CSS URL or Vite dev server URL only for dedicated stylesheet files, omitting component entries such as .vue and .tsx to prevent browser MIME type rejections.

Parameters:

Name Type Description Default
component str

Relative path to the component, e.g. 'components/UserProfile.vue'.

required

Returns:

Type Description
list[str]

List of resolved CSS URLs.

generate_component_css_tags

generate_component_css_tags(component, newline='\n')

Generate HTML link tags for a component's scoped styles.

Parameters:

Name Type Description Default
component str

Relative path to the component entrypoint.

required
newline str

Line ending character to join multiple tags.

'\n'

Returns:

Type Description
str

String of HTML link tags, or empty string if no CSS is associated.

render_fragment

render_fragment(component, props=None, mode='static')

Render a UI component fragment to HTML asynchronously.

Sends render request to the background IPC worker, retrieves the rendered markup, and prepends scoped CSS link tags resolved from manifest.json.

Parameters:

Name Type Description Default
component str

Path to the component entrypoint, e.g. 'components/Counter.vue'.

required
props dict[str, Any] | None

Optional dictionary of component props.

None
mode Literal['static', 'island']

Rendering mode, either 'static' (zero JS) or 'island' (interactive).

'static'

Returns:

Type Description
str

Rendered HTML string with scoped CSS links prepended.

Raises:

Type Description
ImproperlyConfiguredException

If the IPC worker reports a render error.

render_fragment_sync

render_fragment_sync(component, props=None, mode='static')

Render a UI component fragment synchronously for template engines.

Executes the async render_fragment method on the worker loop using anyio. Falls back to anyio.run when no event loop is active on the current thread.

Parameters:

Name Type Description Default
component str

Path to the component entrypoint.

required
props dict[str, Any] | None

Optional dictionary of component props.

None
mode Literal['static', 'island']

Rendering mode.

'static'

Returns:

Type Description
str

Rendered HTML string with scoped CSS links prepended.

close

close()

Close the underlying IPC transport if initialized.

ComponentResponse

Bases: Response[str]

HTTP Response that renders a server-side component fragment.

Renders UI component fragments (React, Vue, Svelte, Astro) into HTML markup for HTMX partial swaps and micro-frontend architectures.

to_asgi_response

to_asgi_response(
    app,
    request,
    *,
    background=None,
    cookies=None,
    encoded_headers=None,
    headers=None,
    is_head_response=False,
    media_type=None,
    status_code=None,
    type_encoders=None,
)

Construct the ASGI response that renders the component fragment.

Parameters:

Name Type Description Default
app Any

The Litestar application instance.

required
request Request[Any, Any, Any]

The incoming request.

required
background BackgroundTask | BackgroundTasks | None

Optional background tasks.

None
cookies Any

Optional cookies.

None
encoded_headers Any

Optional encoded headers.

None
headers dict[str, str] | None

Optional headers dictionary.

None
is_head_response bool

Whether the request is a HEAD request.

False
media_type Any

Response media type.

None
status_code int | None

Optional status code override.

None
type_encoders Any

Type encoders mapping.

None

Returns:

Type Description
ASGIResponse

An ASGIResponse callable that executes the fragment rendering.

vite_fragment

vite_fragment(context, /, component, props=None, mode='static', **kwargs)

Render a component fragment within a Jinja2 template.

Merges explicit props with keyword arguments passed to the template callable.

Example in Jinja template

{{ vite_fragment("components/UserProfile.vue", user=user) }} {{ vite_fragment("components/Counter.tsx", props={"initial": 0}, mode="island") }}

Parameters:

Name Type Description Default
context Mapping[str, Any]

The Jinja2 template context containing the request.

required
component str

Relative path to the component entrypoint.

required
props dict[str, Any] | None

Optional dictionary of component props.

None
mode Literal['static', 'island']

Rendering mode ('static' for HTML only or 'island' for interactive).

'static'
**kwargs Any

Additional props passed as keyword arguments.

{}

Returns:

Type Description
Markup

Markup-safe rendered HTML string with scoped styles.

render_fragment

render_fragment = vite_fragment

SSR IPC Transports

BaseIPCTransport

Bases: Protocol

Protocol defining the asynchronous IPC transport contract.

Attributes:

Name Type Description
is_runningbool

Return True if the transport is running and ready to handle requests.

start

start()

Start or initialize the IPC transport.

close

close()

Gracefully shut down the IPC transport and release all resources.

send_request

send_request(payload, timeout=10.0)

Send a JSON payload and return the response.

Parameters:

Name Type Description Default
payload dict[str, Any]

Request dictionary payload.

required
timeout float

Maximum duration in seconds to wait for a response.

10.0

Returns:

Type Description
dict[str, Any]

Decoded response payload dictionary from the worker.

StdioIPCTransport

Bases: BaseIPCTransport

Asynchronous process transport communicating across stdin and stdout using NDJSON.

Attributes:

Name Type Description
commandlist[str]

Return the worker command list.

cwdPath | None

Return the configured working directory for the worker process.

is_runningbool

Return True if the transport is running and ready to handle requests.

start

start()

Spawn the background worker process and launch asynchronous I/O readers.

send_request

send_request(payload, timeout=10.0)

Send an NDJSON request to the worker and await the correlated response.

Parameters:

Name Type Description Default
payload dict[str, Any]

Request dictionary payload.

required
timeout float

Maximum time in seconds to await response.

10.0

Returns:

Type Description
dict[str, Any]

Worker response dictionary.

Raises:

Type Description
IPCTimeoutError

When response is not received within timeout.

IPCWorkerCrashError

When child worker exits unexpectedly.

IPCError

When worker reports an execution failure.

close

close()

Gracefully terminate worker subprocess and release reader tasks.

WasmIPCTransport

Bases: BaseIPCTransport

In-process SSR transport executing self-contained SSR bundles via QuickJS.

Attributes:

Name Type Description
bundle_pathPath

Return the configured SSR bundle path.

is_runningbool

Return True if the in-process SSR context is initialized and ready.

start

start()

Initialize the dedicated worker thread and evaluate the SSR bundle.

close

close()

Shut down the worker thread and release the QuickJS context.

send_request

send_request(payload, timeout=10.0)

Serialize a request, dispatch it to the in-process SSR worker, and decode the response.

Dispatches are serialized on a single engine thread. timeout bounds the execution of this request only; time spent waiting for an earlier request to finish is not counted, so a queued request never resets a healthy engine.

Parameters:

Name Type Description Default
payload dict[str, Any]

Outbound IPC request dictionary.

required
timeout float

Maximum duration in seconds to wait for a response once dispatched.

10.0

Returns:

Type Description
dict[str, Any]

Decoded response dictionary from the SSR worker.

TCPStreamIPCTransport

Bases: BaseIPCTransport

Send development SSR RPC requests through a pooled HTTP client.

Attributes:

Name Type Description
hoststr

Return the target hostname or IP address.

portint

Return the target TCP port.

pathstr

Return the configured HTTP endpoint path.

schemestr

Return the endpoint protocol.

is_runningbool

Return True because connections are established lazily on the next request.

start

start()

Initialize the client connection pool if needed.

close

close()

Release pooled connections.

send_request

send_request(payload, timeout=10.0)

Send an RPC request within a total deadline and validate its response.

Raises:

Type Description
IPCTimeoutError

The request exceeded its total deadline.

IPCError

The connection failed or the server returned an invalid response.

resolve_ssr_transport

resolve_ssr_transport(config=None, ssr_config=None)

Resolve the production SSR IPC transport according to runtime configuration and host capabilities.

Resolution order
  1. runtime.ssr_transport == "wasm" -> WasmIPCTransport.
  2. runtime.ssr_transport == "stdio" -> StdioIPCTransport using resolve_ssr_command.
  3. runtime.ssr_transport == "auto" (default): a. Explicit ssr_config.command -> StdioIPCTransport. b. Configured JS runtime binary available on PATH or venv -> StdioIPCTransport. c. is_wasm_available() is True -> WasmIPCTransport fallback. d. Default to StdioIPCTransport using resolve_ssr_command.

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
BaseIPCTransport

Configured BaseIPCTransport instance for production SSR.

is_wasm_available

is_wasm_available()

Return True when the in-process QuickJS runtime (litestar-vite[wasm]) is importable.

IPCRequest

Structured representation of an outbound JSON-RPC/NDJSON IPC request payload.

Attributes:

Name Type Description
idint

Monotonically increasing request correlation identifier.

methodstr

RPC method name ('ssr', 'fragment', 'ping', or 'shutdown').

paramsdict[str, Any] | None

Optional JSON-serializable parameters dictionary passed to the worker method.

to_dict
to_dict()

Convert the request into a JSON-serializable dictionary.

Returns:

Type Description
dict[str, Any]

Dictionary payload adhering to the RPC framing contract.

IPCResponse

Structured representation of an inbound JSON-RPC/NDJSON IPC response payload.

Attributes:

Name Type Description
idint

Correlation identifier matching the originating IPCRequest.id.

resultAny

Decoded response payload returned by the worker when successful.

errorstr | None

Error message string returned by the worker when execution fails.


Circuit Breaker & IPC Exceptions

SSRCircuitBreaker

Three-state circuit breaker pattern for SSR worker stability.

Attributes:

Name Type Description
stateCircuitState

Return the current circuit state, evaluating cooldown if currently OPEN.

failure_countint

Return the current consecutive failure tally.

failure_thresholdint

Return the threshold of failures required to open the circuit.

cooldownfloat

Return the configured cooldown period in seconds.

reset_timeoutfloat

Return the configured reset timeout in seconds.

can_execute

can_execute()

Determine whether an outbound request is permitted through the breaker.

Returns:

Type Description
bool

True if request is allowed, False if breaker is open.

allow_request

allow_request()

Return whether an outbound request is permitted through the circuit breaker.

Returns:

Type Description
bool

True if request is allowed, False if breaker is open.

record_success

record_success()

Record a successful execution, resetting failures and closing the circuit.

record_failure

record_failure(exc=None)

Record an execution failure, potentially tripping the circuit to OPEN.

Parameters:

Name Type Description Default
exc BaseException | None

Optional exception that caused the failure.

None

reset

reset()

Manually reset the circuit breaker to closed state.

CircuitState

Bases: str, Enum

Lifecycle states of the SSR circuit breaker.

IPCError

Bases: Exception

Base exception for all IPC errors.

IPCTimeoutError

Bases: IPCError

Raised when an IPC request exceeds the configured timeout threshold.

IPCWorkerCrashError

Bases: IPCError

Raised when an IPC child worker terminates unexpectedly.

CircuitBreakerOpenError

Bases: IPCError

Raised when an IPC request is attempted while the circuit breaker is open.