Litestar vite

From litestar-org/litestar-skills · View interactive version

Litestar vite is an AI agent skill from the GitHub repository litestar-org/litestar-skills. Use when working with litestar_vite, VitePlugin, ViteConfig, PathConfig, TypeGenConfig, vite.config.ts, InertiaConfig, component=, or @inertiajs/*. Not for plain Vite or server-only HTMX.

How to use this skill

Skill file

litestar-vite

litestar-vite is the first-party plugin that connects a Vite frontend build pipeline to a Litestar backend. It handles dev-server proxying, HMR coordination, manifest resolution for production assets, and (optionally) end-to-end type generation from Litestar OpenAPI to TypeScript.

The runtime has four canonical modes: spa, template, hybrid, and framework.

htmx, inertia, ssr, and ssg are aliases that normalize to those modes.

external is a fifth, permanent alias of framework; it still requires an ExternalDevServer.

The plugin pairs with the npm package CODE0 on the JS side. Python ViteConfig is the source of truth; the generated .litestar.json bridge lets JS config normally keep only litestar({ input: [...] }).

This guidance targets litestar-vite 0.34.0. Features include server-rendered UI component fragments, persistent stdio and QuickJS WASM (WasmIPCTransport) SSR transports with circuit-breaker and memory/stack caps, lockfile JS runtime auto-detection (detect_runtime), RFC 8288 Link preload / 103 Early Hints / immutable cache headers, route-filtered AsyncAPI/TypeGen (only_routes/exclude_routes), Vite 7+/8+ support, and loopback-first single-port dev proxying (VITE_ALLOW_REMOTE=1 for remote hosts). See Release Updates.

Code Style Rules

Quick Reference

Minimal SPA setup (Python side)

from litestar import Litestar
from litestar_vite import PathConfig, ViteConfig, VitePlugin

vite_config = ViteConfig(
    mode="spa",
    enabled=True,
    paths=PathConfig(
        resource_dir="resources",
        bundle_dir="public",
        hot_file="hot",
    ),
    dev_mode=True,
)

app = Litestar(plugins=[VitePlugin(config=vite_config)])

Minimal SPA setup (JS side)

// vite.config.ts
import { defineConfig } from "vite"
import litestar from "litestar-vite-plugin"
import react from "@vitejs/plugin-react"

export default defineConfig({
  clearScreen: false,
  publicDir: "public",
  plugins: [
    react(),
    litestar({
      input: ["resources/main.tsx", "resources/main.css"],
    }),
  ],
  resolve: { alias: { "@": "/resources" } },
})

Mode Selection

| Mode | Use For | Key Setup |

| --- | --- | --- |

| spa | React, Vue, Svelte, or Analog-powered Angular SPA with a Litestar JSON API backend | dev_mode=True proxies to Vite; manifest in prod |

| template (htmx alias) | Server-rendered Jinja2/Mako pages and HTMX with Vite-bundled assets | Use TemplateConfig; add litestar-htmx when using HTMX |

| hybrid (inertia alias) | Inertia.js routes returning JS page components | Configure ViteConfig(inertia=InertiaConfig(...)) |

| framework (ssr / ssg aliases) | Nuxt, SvelteKit, Astro, Angular CLI, or another frontend-owned HTML server | Use the framework entry point or ExternalDevServer |

Decision tree:

`VitePlugin` config (Python)

from litestar_vite import (
    PathConfig,
    RuntimeConfig,
    TypeGenConfig,
    ViteConfig,
    VitePlugin,
)

vite_config = ViteConfig(
    mode="spa",
    enabled=True,
    dev_mode=False,
    paths=PathConfig(
        root=".",
        resource_dir="src",
        bundle_dir="public",
        static_dir="src/public",
        hot_file="hot",
        asset_url="/static/",
    ),
    runtime=RuntimeConfig(
        port=5173,
        host="127.0.0.1",
        protocol="http",
        executor="bun",
    ),
    types=TypeGenConfig(
        generate_zod=False,
        generate_sdk=True,
        generate_routes=True,
        generate_schemas=True,
        generate_page_props=False,
        only_routes=(),
        exclude_routes=(),
        output="src/generated",
    ),
)

enabled=None auto-detects serving contexts and consults VITE_ENABLED.

enabled=False leaves VitePlugin.config and asset CLI commands available but

skips runtime routes, middleware, static routers, lifespans, and the SPA

handler.

Type Generation

TypeGenConfig(
    generate_sdk=True,
    generate_routes=True,
    generate_schemas=True,
    generate_page_props=True,
    output="src/generated",
)

| Output | Path | Trigger | Frontend Use |

| --- | --- | --- | --- |

| openapi.json | output/openapi.json | Whenever OpenAPI schema changes | Source of truth for SDK + schemas |

| routes.json | output/routes.json | Route table changes | Route metadata consumed by the JS plugin |

| routes.ts | output/routes.ts | Route table or app.csrf_config changes | route("name", { params }) typed URL builder + CSRF_COOKIE_NAME / CSRF_HEADER_NAME (0.31.0+) |

| api/ | output/api/ | OpenAPI changes | hey-api types, schemas, SDK, and fetch client |

| schemas.ts | output/schemas.ts | Route request/response changes | FormInput, FormResponse, and SuccessResponse helpers |

| inertia-pages.json | output/inertia-pages.json | Inertia handlers added/changed | Page-prop metadata consumed by the JS plugin |

| page-props.ts | output/page-props.ts | Inertia handlers added/changed | Typed props for Inertia page components |

| static-props.ts | output/static-props.ts | ViteConfig.static_props changes | Typed static bridge values (virtual:litestar-static-props) |

| asyncapi.json | output/asyncapi.json | AsyncAPIPlugin + Channels / WebSocket / SSE route changes (0.32.0+) | AsyncAPI 3.0 document when AsyncAPIPlugin is registered and generate_channels=True |

| channels.ts | output/channels.ts | AsyncAPIPlugin + Channels / WebSocket / SSE route changes (0.32.0+) | ChannelMap consumed by createTypedChannels() |

CLI:

litestar assets generate-types          # one-off generation
litestar assets export-routes           # routes.json metadata (--only, --except, --include-components)
litestar assets export-routes --typescript  # routes.ts only
litestar --app app:app run              # generates on startup if enabled

Frontend consumption:

// routes + CSRF constants (0.31.0+)
import { CSRF_COOKIE_NAME, CSRF_HEADER_NAME, route } from "@/generated/routes"
import { csrfFetch, csrfHeaders, getCsrfHeaderName, getCsrfToken } from "litestar-vite-plugin/helpers"
const url = route("users:get", { id: 123 })
await csrfFetch(url, { method: "POST" }, { headerName: CSRF_HEADER_NAME, cookieName: CSRF_COOKIE_NAME })

// hey-api output
import type { User } from "@/generated/api"

// ergonomic route helpers
import type { FormInput } from "@/generated/schemas"
type LoginInput = FormInput<"auth:login">

`ViteAssetLoader`, Secondary HTML Entries, and Component Fragments

Auto-registered Jinja2 globals when mode="template" and JinjaTemplateEngine is configured (vite_asset aliases vite):

| Helper | Use |

| --- | --- |

| {{ vite('resources/main.ts') }} | Render script/link tags for a Vite input; handles dev vs manifest |

| {{ vite_hmr() }} | Inject HMR client <script> in dev mode; no-op in prod |

| {{ vite_static('favicon.svg') }} | Resolve a static asset URL |

| {{ vite_routes() }} | Render inline route metadata for client-side routing |

| {{ vite_fragment('components/Card.vue', props=..., mode='static') }} | Server-render a React/Vue/Svelte/Astro fragment or <litestar-island> (0.32.0+) |

Minimal base template:

<!DOCTYPE html>
<html>
<head>
  {{ vite_hmr() }}
  {{ vite('resources/main.tsx') }}
</head>
<body>
  <div id="app"></div>
</body>
</html>

For programmatic asset loading (ViteAssetLoader, resolve_html_entry) or server-rendered <litestar-island> UI component fragments (ComponentResponse(..., mode="island")), see Modes and Config.

CLI

litestar assets init             # Scaffold vite.config.ts and package.json
litestar assets install          # Run npm/pnpm/bun install
litestar assets update           # Update within package.json semver ranges
litestar assets serve            # Start Vite dev server (also auto-started when `dev_mode=True`)
litestar assets build            # Production build (emits manifest.json + hashed bundles)
litestar assets deploy --dry-run # Build and preview an fsspec-backed deployment
litestar assets deploy           # Build and sync to DeployConfig.storage_backend
litestar assets generate-types   # TypeScript type generation
litestar assets export-routes    # routes.json metadata
litestar assets doctor           # Diagnose integration health
litestar assets status           # Read-only status summary

assets init --template accepts react, react-router, react-tanstack, react-inertia, react-inertia-jinja, vue, vue-inertia, vue-inertia-ssr, vue-inertia-jinja, vue-inertia-jinja-ssr, svelte, svelte-inertia, svelte-inertia-jinja, sveltekit, nuxt, astro, htmx, jinja-htmx, htmx-no-jinja, angular, and angular-cli.

HMR & Production Build

Inertia & HTMX Integration

<workflow>

Workflow

  1. Pick the Mode: Select spa, template, hybrid (Inertia), or framework.
  2. Install: Run pip install litestar-vite and npm install -D vite litestar-vite-plugin (or scaffold with litestar assets init --template <name>).
  3. Wire ViteConfig (Python): Configure PathConfig, optional RuntimeConfig, optional InertiaConfig (for hybrid), and optional TypeGenConfig. Toggle dev_mode from an environment variable and register VitePlugin(config=...).
  4. Wire vite.config.ts (JS): Add litestar({ input: [...] }) and let .litestar.json supply bundleDir, hotFile, typegen paths, and assetUrl.
  5. Enable TypeGen (Optional): Set types=TypeGenConfig(...) and run litestar assets generate-types when DTOs or component= routes change.
  6. Wire Templates or Inertia Pages: Use vite_hmr() + vite() in templates (with HTMXPlugin() for HTMX), or createInertiaApp() with csrfHeaders() and usePage().flash in hybrid mode.
  7. Verify HMR & Build: Run litestar run in dev (single-port proxy) and litestar assets build (or litestar assets deploy) with dev_mode=False in production.

</workflow>

<guardrails>

Guardrails

asset HTTP and HMR. RuntimeConfig.proxy_mode accepts "vite", "proxy",

or None; legacy VITE_PROXY_MODE=direct warns and becomes "vite".

removes the need for frontend CORS.

</guardrails>

<validation>

Validation Checkpoint

Before delivering a litestar-vite integration, verify:

manifest plus hashed bundles

litestar assets deploy --dry-run before deployment

</validation>

<example>

Example

Task: A Litestar SPA app with React + TanStack Router + Tailwind, building into the Litestar static dir, with HMR in dev.

"""app/config/vite.py"""

import os
from pathlib import Path

from litestar_vite import PathConfig, RuntimeConfig, ViteConfig

PROJECT_ROOT = Path(__file__).resolve().parents[3]
FRONTEND_ROOT = PROJECT_ROOT / "src/js/web"
STATIC_DIR = PROJECT_ROOT / "src/py/app/server/static/web"

vite = ViteConfig(
    paths=PathConfig(
        root=FRONTEND_ROOT,
        bundle_dir=STATIC_DIR,
        hot_file="hot",
        asset_url="/static/web/",
    ),
    runtime=RuntimeConfig(port=3006, executor="bun", is_react=True),
    dev_mode=os.getenv("ENV", "dev") == "dev",
)
"""app/server/plugins.py"""

from app import config
from litestar_vite import VitePlugin

vite = VitePlugin(config=config.vite)
// src/js/web/vite.config.ts
import path from "node:path"
import tailwindcss from "@tailwindcss/vite"
import { tanstackRouter } from "@tanstack/router-plugin/vite"
import react from "@vitejs/plugin-react"
import litestar from "litestar-vite-plugin"
import { defineConfig } from "vite"

export default defineConfig({
  clearScreen: false,
  base: process.env.ASSET_URL ?? "/static/web/",
  publicDir: "public",
  server: { port: Number(process.env.VITE_PORT ?? 3006) }, // optional internal port pin
  build: {
    outDir: path.resolve(__dirname, "../../py/app/server/static/web"),
    emptyOutDir: true,
  },
  plugins: [
    tanstackRouter({ target: "react", autoCodeSplitting: true }),
    tailwindcss(),
    react(),
    litestar({
      input: ["src/main.tsx", "src/styles.css"],
      bundleDir: path.resolve(__dirname, "../../py/app/server/static/web"), // explicit override
      hotFile: path.resolve(__dirname, "../../py/app/server/static/web/hot"), // explicit override
    }),
  ],
  resolve: { alias: { "@": path.resolve(__dirname, "./src") } },
})
# Dev - Litestar boots Vite alongside the ASGI server
litestar --app app:app run

# Prod build
ENV=prod litestar assets build

</example>


References Index

For deep-dives on specific surfaces, see:

Cross-References

Official References

Shared Styleguide Baseline

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.