### Development environment setup Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/PYPI_README.md Commands to install dependencies and run an example application. ```bash # Install Python, docs, and JS dependencies; build package artifacts make install && make build # Run an example app uv run litestar --app-dir examples/vue-inertia assets install uv run litestar --app-dir examples/vue-inertia run ``` -------------------------------- ### Install example dependencies Source: https://github.com/litestar-org/litestar-vite/blob/main/examples/README.md Navigate to the specific example directory and install required npm packages. ```bash cd examples/{example-name} npm install ``` -------------------------------- ### Getting Started with Litestar Fullstack Inertia Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/fullstack-example.rst Commands to clone the template, install dependencies, and run the development server. ```bash git clone https://github.com/litestar-org/litestar-fullstack-inertia.git cd litestar-fullstack-inertia make install make run ``` -------------------------------- ### Install Dependencies Source: https://github.com/litestar-org/litestar-vite/blob/main/CONTRIBUTING.rst Installs all project dependencies and pre-commit hooks. ```bash make install ``` -------------------------------- ### Install and Run Litestar-Vite Source: https://github.com/litestar-org/litestar-vite/blob/main/llms.txt Commands to install the package, scaffold a frontend template, and start the development server. ```bash pip install litestar-vite litestar assets init --template vue # scaffold frontend (react, svelte, htmx, etc.) litestar run --reload # Vite dev server proxied automatically ``` -------------------------------- ### Manual Frontend Setup Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/usage/vite.rst Manually initialize the frontend project and install dependencies. ```bash npm init -y npm install vite npm install -D litestar-vite-plugin ``` ```bash litestar assets install ``` -------------------------------- ### Initialize and run assets Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/PYPI_README.md Commands to scaffold a frontend template, install dependencies, and start the development server. ```bash litestar assets init --template vue litestar assets install litestar run --reload ``` -------------------------------- ### Backend Setup Example Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/sveltekit.rst Example Python code for setting up the Litestar backend in a SvelteKit project. ```python from litestar import Litestar app = Litestar( route_prefix="/api" ) ``` -------------------------------- ### Run Development Server Source: https://github.com/litestar-org/litestar-vite/blob/main/examples/react-router/README.md Command to start the Litestar development server for the React Router example. ```bash litestar --app-dir examples/react-router run ``` -------------------------------- ### Run the development server Source: https://github.com/litestar-org/litestar-vite/blob/main/examples/README.md Start the Litestar application for a specific example using the development server. ```bash uv run litestar --app-dir examples/{example-name} run ``` -------------------------------- ### Install Pre-releases Source: https://github.com/litestar-org/litestar-vite/blob/main/CONTRIBUTING.rst Commands to install pre-release versions of the package for Python and npm. ```bash # Python pip install litestar-vite==0.15.0a1 # or allow any pre-release pip install --pre litestar-vite # npm npm install litestar-vite-plugin@next # or specific version npm install litestar-vite-plugin@0.15.0-alpha.1 ``` -------------------------------- ### Litestar Backend Setup Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/astro.rst Example Python code for the Litestar backend application. ```python from litestar import Litestar from litestar.config.app import AppConfig from litestar.contrib.vite import ViteConfig app = Litestar( route_prefix="/api", config=AppConfig( plugins=[ ViteConfig( mode="ssg", # or "framework" # Optional: Set to True to start the Astro dev server # start_dev_server=True ) ] ) ) ``` -------------------------------- ### DeployConfig example Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/usage/production.rst Example of configuring deploy settings for Litestar Vite plugin. ```python from litestar_vite import DeployConfig, ViteConfig, VitePlugin VitePlugin( config=ViteConfig( deploy=DeployConfig( storage_backend="s3://bucket/assets", asset_url="https://cdn.example.com/assets/", ) ) ) ``` -------------------------------- ### Run commands Source: https://github.com/litestar-org/litestar-vite/blob/main/examples/vue-inertia-jinja-ssr/README.md Commands to install assets, build for SSR, start the SSR server, and run the Litestar application. ```bash litestar --app-dir examples/vue-inertia-jinja-ssr assets install npm --prefix examples/vue-inertia-jinja-ssr run build:ssr npm --prefix examples/vue-inertia-jinja-ssr run start:ssr # Terminal 1 litestar --app-dir examples/vue-inertia-jinja-ssr run # Terminal 2 ``` -------------------------------- ### Install VHS Source: https://github.com/litestar-org/litestar-vite/blob/main/CONTRIBUTING.rst Installs the VHS terminal recorder on macOS using Homebrew or on Linux using Go. ```bash # macOS brew install vhs # Linux (with Go installed) go install github.com/charmbracelet/vhs@latest ``` -------------------------------- ### Backend Setup (Vite-based) Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/angular.rst Example Litestar backend setup with Vite plugin integration. ```python from pathlib import Path from typing import Any from litestar import Litestar, get from litestar_vite import ViteConfig, VitePlugin from litestar_vite.config import PathConfig @get("/api/hello") async def hello() -> dict[str, Any]: return {"message": "Hello from Litestar!"} vite = VitePlugin(config=ViteConfig(dev_mode=True)) app = Litestar( plugins=[vite], route_handlers=[hello], ) ``` -------------------------------- ### Implement Header Component Source: https://github.com/litestar-org/litestar-vite/blob/main/examples/README.md Standard header structure for all framework examples. ```html

Litestar · Vite

Library ({Framework Name})

Same API, different frontend. {Framework description}.

``` -------------------------------- ### Install Inertia.js client and litestar-vite-plugin for Vue Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/installation.rst Install the Inertia.js client and litestar-vite-plugin for Vue. ```bash npm install @inertiajs/vue3 litestar-vite-plugin ``` -------------------------------- ### Install Inertia.js client and litestar-vite-plugin for React Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/installation.rst Install the Inertia.js client and litestar-vite-plugin for React. ```bash npm install @inertiajs/react litestar-vite-plugin ``` -------------------------------- ### Backend Setup (SPA Mode) Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/react.rst Example of a Litestar backend setup for SPA mode with Vite. ```python from litestar import Litestar from litestar.types import TypeGenConfig app = Litestar( route_list=[ # ... your routes here ... ], openapi_config={ "type_generation": TypeGenConfig() }, # ... other configs ... ) ``` -------------------------------- ### Run (two processes) Source: https://github.com/litestar-org/litestar-vite/blob/main/examples/vue-inertia-ssr/README.md Commands to build the SSR bundle, start the Node SSR server, and start Litestar. ```bash # Terminal 1 — build the SSR bundle once, then start the Node /render server litestar --app-dir examples/vue-inertia-ssr assets install npm --prefix examples/vue-inertia-ssr run build:ssr npm --prefix examples/vue-inertia-ssr run start:ssr # Terminal 2 — start Litestar (auto-starts Vite dev server) litestar --app-dir examples/vue-inertia-ssr run ``` -------------------------------- ### Install Inertia.js client and litestar-vite-plugin for Svelte Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/installation.rst Install the Inertia.js client and litestar-vite-plugin for Svelte. ```bash npm install @inertiajs/svelte litestar-vite-plugin ``` -------------------------------- ### Meta-Frameworks Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/index.rst Scaffolds meta-framework projects like Astro, Nuxt, and SvelteKit. ```bash litestar assets init --template astro litestar assets init --template nuxt litestar assets init --template sveltekit ``` -------------------------------- ### Frontend component implementation Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/pages.rst Examples of how to consume props in different frontend frameworks. ```tsx // pages/Users/Show.tsx interface Props { user: { id: number; name: string; email: string }; } export default function Show({ user }: Props) { return (

{user.name}

{user.email}

); } ``` ```vue ``` ```svelte

{user.name}

{user.email}

``` -------------------------------- ### SPA & Templates Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/index.rst Scaffolds various SPA and template-based frontend projects. ```bash litestar assets init --template react litestar assets init --template vue litestar assets init --template svelte litestar assets init --template angular litestar assets init --template angular-cli litestar assets init --template htmx ``` -------------------------------- ### Create a Standard Release Source: https://github.com/litestar-org/litestar-vite/blob/main/CONTRIBUTING.rst Command to bump the version for a standard release. ```bash make release bump=major|minor|patch ``` -------------------------------- ### Install litestar-vite using uv Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/installation.rst Install the litestar-vite Python package using uv. ```bash uv add litestar-vite ``` -------------------------------- ### Create an Alpha Pre-release Source: https://github.com/litestar-org/litestar-vite/blob/main/CONTRIBUTING.rst Commands to create alpha, beta, and release candidate pre-releases. ```bash # Start an alpha release make pre-release version=0.15.0-alpha.1 # Subsequent alphas make pre-release version=0.15.0-alpha.2 # Progress to beta make pre-release version=0.15.0-beta.1 # Release candidate make pre-release version=0.15.0-rc.1 ``` ```bash git push origin HEAD ``` ```bash gh release create v0.15.0-alpha.1 --prerelease --title "v0.15.0-alpha.1" ``` -------------------------------- ### Client-Side Fetch Example Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/sveltekit.rst Example Svelte component demonstrating client-side data fetching using `onMount`. ```svelte {#if summary}

{summary.headline}

{/if} ``` -------------------------------- ### Generate GIF for Documentation Source: https://github.com/litestar-org/litestar-vite/blob/main/CONTRIBUTING.rst Commands to generate a GIF for documentation and how to reference it. ```bash make docs-demos ``` ```rst .. image:: /_static/demos/your-demo.gif ``` -------------------------------- ### Install litestar-vite using pdm Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/installation.rst Install the litestar-vite Python package using pdm. ```bash pdm add litestar-vite ``` -------------------------------- ### Install Litestar Vite dependencies Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/PYPI_README.md Install the required Python package and the corresponding Vite plugin via npm. ```bash pip install litestar-vite npm install litestar-vite-plugin ``` -------------------------------- ### Guard-based sharing Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/fullstack-example.rst Example of using a guard to share authentication data with Inertia. ```python async def auth_guard(connection: ASGIConnection, _: BaseRouteHandler) -> None: share(connection, "auth", { "isAuthenticated": bool(connection.user), "user": serialize_user(connection.user), }) ``` -------------------------------- ### Vite Configuration Example Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/sveltekit.rst Example TypeScript code for configuring Vite with the Litestar SvelteKit plugin. ```typescript import { defineConfig } from 'vite' import { litestarSvelteKit } from '@litestar/vite-plugin' import sveltekit from '@sveltejs/kit/vite' export default defineConfig({ plugins: [ litestarSvelteKit(), sveltekit(), ], }) ``` -------------------------------- ### Backend Usage Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/once-props.rst Example of using `once` to cache props on the backend. ```python from typing import Any from litestar import get from litestar_vite.inertia import once @get("/dashboard", component="Dashboard") async def dashboard() -> dict[str, Any]: return { "user": get_current_user(), "feature_flags": once("feature_flags", get_feature_flags), "settings": once("settings", lambda: Settings.for_user("alice")), } ``` -------------------------------- ### Svelte Component Example (src/routes/users/+page.svelte) Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/sveltekit.rst Example Svelte component to display a list of users fetched via a load function. ```svelte

Users

``` -------------------------------- ### Install Source: https://github.com/litestar-org/litestar-vite/blob/main/src/js/README.md Install the litestar-vite-plugin using npm. ```bash npm install litestar-vite-plugin ``` -------------------------------- ### Inertia Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/index.rst Scaffolds Inertia.js projects for React, Vue, and Svelte. ```bash litestar assets init --template react-inertia litestar assets init --template vue-inertia litestar assets init --template svelte-inertia # Template-mode examples: react-inertia-jinja / vue-inertia-jinja ``` -------------------------------- ### SvelteKit Load Function Example (src/routes/users/+page.ts) Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/sveltekit.rst Example of a SvelteKit load function for fetching user data on the client-side or during SSR. ```typescript // src/routes/users/+page.ts import type { PageLoad } from './$types' import type { User } from '$lib/generated/types.gen' import { route } from '$lib/generated/routes' export const load: PageLoad = async ({ fetch }) => { const response = await fetch(route('users:list')) const users: User[] = await response.json() return { users } } ``` -------------------------------- ### Backend Setup (app.py) Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/nuxt.rst Litestar backend setup for Nuxt SSR integration. ```python from litestar import Litestar from litestar.config.response import ResponseConfig from litestar.contrib.vite import ViteSettings from litestar.contrib.vite.config import ViteConfig settings = ViteSettings( mode="ssr", # or "framework" dev_server_port=3000, static_dir="dist", build_dir="dist", assets_dir="assets", resource_dir="resources", template_dir="templates", dev_assets_dir="assets", dev_template_dir="templates", dev_resource_dir="resources", ) app = Litestar( route_prefix="/", settings=settings, response_cache_config=ResponseConfig(max_age=600), ) ``` -------------------------------- ### SvelteKit Server Load Function Example (src/routes/users/+page.server.ts) Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/sveltekit.rst Example of a SvelteKit server-only load function for fetching user data directly from the backend API. ```typescript // src/routes/users/+page.server.ts import type { PageServerLoad } from './$types' import type { User } from '$lib/generated/types.gen' export const load: PageServerLoad = async ({ fetch }) => { const response = await fetch('http://localhost:8000/api/users') const users: User[] = await response.json() return { users } } ``` -------------------------------- ### Quick Start Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/htmx.rst Command to initialize a new Litestar project with HTMX template. ```bash litestar assets init --template htmx ``` -------------------------------- ### app.py Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/usage/index.rst Example of setting up Litestar with VitePlugin in development mode. ```python from pathlib import Path from litestar import Litestar from litestar_vite import PathConfig, ViteConfig, VitePlugin app = Litestar( plugins=[ VitePlugin( config=ViteConfig( dev_mode=True, paths=PathConfig(root=Path(__file__).parent), ) ) ] ) ``` -------------------------------- ### Version Header Example Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/asset-versioning.rst The version is included in response headers. ```text X-Inertia: true X-Inertia-Version: a1b2c3d4 ``` -------------------------------- ### Litestar Integration - Simple Inertia route Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/how-it-works.rst Example of a simple Inertia route in Litestar. ```python from typing import Any from litestar import get # Simple Inertia route @get("/dashboard", component="Dashboard") async def dashboard() -> dict[str, Any]: return {"user": "Alice", "stats": {"views": 100}} # The plugin handles: # 1. Detecting X-Inertia header # 2. Building PageProps object # 3. Returning JSON or HTML based on request type # 4. Version checking ``` -------------------------------- ### Project Structure Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/fullstack-example.rst Overview of the directory structure for the Litestar Fullstack Inertia project. ```text litestar-fullstack-inertia/ ├── src/ │ └── app/ │ ├── domain/ # Business logic │ │ ├── accounts/ # User accounts │ │ ├── teams/ # Team management │ │ └── system/ # System utilities │ ├── server/ # Litestar server │ │ ├── plugins.py # Plugin configuration │ │ └── routes.py # Route registration │ └── lib/ # Shared utilities ├── resources/ # Frontend assets │ ├── main.ts # Entry point │ ├── pages/ # Inertia page components │ └── components/ # Reusable components └── templates/ └── index.html # Root template ``` -------------------------------- ### Initialize Vite Project via CLI Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/usage/vite.rst Use the CLI to initialize a new Vite project with various template options. ```bash # Initialize a new Vite project (React default) litestar assets init # Available templates: # SPA: react, react-router, react-tanstack, vue, svelte # Inertia: react-inertia, vue-inertia, svelte-inertia # Inertia template-mode examples (Jinja): react-inertia-jinja, vue-inertia-jinja # SSR: sveltekit, nuxt, astro # Other: angular, angular-cli, htmx # Inertia templates keep Laravel-style paths under resources/ litestar assets init --template vue-inertia # Non-Inertia templates default to src/; place everything under web/ litestar assets init --template react-router --frontend-dir web ``` -------------------------------- ### Implement Library Controller API Source: https://github.com/litestar-org/litestar-vite/blob/main/examples/README.md Defines the standard Library backend endpoints and data structures required for all example applications. ```python from litestar import Controller, get from litestar.params import FromPath from msgspec import Struct class Book(Struct): id: int title: str author: str year: int tags: list[str] class Summary(Struct): app: str headline: str total_books: int featured: Book BOOKS: list[Book] = [ Book(id=1, title="Async Python", author="C. Developer", year=2024, tags=["python", "async"]), Book(id=2, title="Type-Safe Web", author="J. Dev", year=2025, tags=["typescript", "api"]), Book(id=3, title="Frontend Patterns", author="A. Designer", year=2023, tags=["frontend", "ux"]), ] class LibraryController(Controller): @get("/api/summary") async def summary(self) -> Summary: return Summary( app="litestar-vite library", headline="One backend, many frontends", total_books=len(BOOKS), featured=BOOKS[0], ) @get("/api/books") async def books(self) -> list[Book]: return BOOKS @get("/api/books/{book_id:int}") async def book_detail(self, book_id: FromPath[int]) -> Book: # Return book or raise NotFoundException ... ``` -------------------------------- ### Transition from Pre-release to Stable Source: https://github.com/litestar-org/litestar-vite/blob/main/CONTRIBUTING.rst Command to remove the pre-release suffix when transitioning from an RC to a stable release. ```bash make release bump=pre ``` -------------------------------- ### Implement Overview Section Source: https://github.com/litestar-org/litestar-vite/blob/main/examples/README.md Display layout for the featured book in the overview tab. ```html

{headline}

Featured book

{title}

{author} • {year}

{tags}

``` -------------------------------- ### Python Setup for Static Props Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/usage/static-props.rst Example of adding static props to your ViteConfig in Litestar. ```python from litestar_vite import ViteConfig, VitePlugin app = Litestar( plugins=[ VitePlugin( config=ViteConfig( static_props={ "appName": "My Application", "version": "1.0.0", "environment": "production", "features": { "darkMode": True, "analytics": False, }, } ) ) ] ) ``` -------------------------------- ### Litestar Backend Setup (SPA Mode) Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/svelte.rst Example of a Litestar backend configuration for SPA mode with Vite. ```python from litestar import Litestar from litestar.types.asgi import ASGIReceiveEvent, ASGISendEvent from litestar.contrib.vite import ViteConfig, VitePlugin class TypeGenConfig: pass async def app( scope: ASGIReceiveEvent, receive: ASGISendEvent, next_app: callable[..., ASGIReceiveEvent], ) -> None: pass app = Litestar( route_handlers=[ app ], plugins=[ VitePlugin(config=ViteConfig(mode="spa")) ], type_engine=TypeGenConfig(), ) ``` -------------------------------- ### Vue Manual Start/Stop Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/polling.rst Example of disabling auto-start for `usePoll` in Vue and controlling the polling manually using `start()` and `stop()` methods. ```vue ``` -------------------------------- ### React Manual Start/Stop Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/polling.rst Example of disabling auto-start for `usePoll` in React and controlling the polling manually using `start()` and `stop()` methods. ```tsx import { usePoll } from "@inertiajs/react"; const poll = usePoll(2000, {}, { autoStart: false }); poll.start(); poll.stop(); ``` -------------------------------- ### Run Production Build Source: https://github.com/litestar-org/litestar-vite/blob/main/examples/react-router/README.md Command to run the Litestar application in production mode, disabling Vite's development mode. ```bash VITE_DEV_MODE=false litestar --app-dir examples/react-router run ``` -------------------------------- ### Litestar Backend Setup (SPA Mode) Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/vue.rst Example Python code for a Litestar backend serving API endpoints in SPA mode with Vite integration. ```python from litestar import Litestar from litestar.contrib.vite import VitePlugin from litestar.types import Scope from litestar.contrib.types import TypeGenConfig def on_request(scope: Scope, receive, send): if scope["type"] == "http": # Handle SPA routing if scope["path"] == "/": scope["path"] = "/index.html" return app(scope, receive, send) app = Litestar( route_handlers=[...], plugins=[ VitePlugin(mode="spa", type_render_class=TypeGenConfig()) ], ) ``` -------------------------------- ### Customizing Server Error Handling Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/error-handling.rst Example of how to customize the Inertia app setup to handle server errors, specifically showing a custom error page instead of the default modal. ```tsx import { createInertiaApp } from "@inertiajs/svelte"; import ErrorPage from "./ErrorPage.svelte"; // Assuming ErrorPage is a Svelte component createInertiaApp({ resolve: (name) => pages[`./pages/${name}.tsx`], setup({ el, App, props }) { createRoot(el).render( }> ); }, }); ``` -------------------------------- ### Initial Load (Full HTML) - Default script-element bootstrap Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/how-it-works.rst Default script-element bootstrap for initial page load. ```html
``` -------------------------------- ### Initial Load (Full HTML) - Classic data-page bootstrap Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/how-it-works.rst Classic data-page bootstrap for initial page load. ```html
``` -------------------------------- ### litestar assets init Source: https://github.com/litestar-org/litestar-vite/blob/main/llms-full.txt Initialize a Vite project with specified framework templates. ```APIDOC ## litestar assets init ### Description Initialize Vite project with framework templates. ### Options - **--template** - Template to use (e.g., react, vue, svelte) - **--root-path** - Project root path - **--frontend-dir** - Frontend directory - **--bundle-path** - Bundle path - **--resource-path** - Resource path - **--static-path** - Static path - **--asset-url** - Asset URL - **--vite-port** - Vite server port - **--enable-ssr / --disable-ssr** - Toggle SSR support - **--tailwind** - Enable Tailwind CSS - **--enable-types** - Enable type support - **--generate-zod** - Generate Zod schemas - **--generate-client** - Generate client code - **--overwrite** - Overwrite existing files - **--verbose** - Enable verbose output - **--no-prompt** - Run without interactive prompts - **--no-install** - Skip package installation ``` -------------------------------- ### Initialize Inertia Configuration Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/configuration.rst Basic server-side initialization for the Inertia configuration. ```python from litestar_vite import InertiaConfig InertiaConfig() ``` -------------------------------- ### Configure SPA Mode Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/templates.rst Use ViteConfig for SPA mode and define the index.html file. ```python ViteConfig( inertia=InertiaConfig(), ) ``` ```html
``` -------------------------------- ### Install litestar-vite using pip Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/installation.rst Install the litestar-vite Python package using pip. ```bash pip install litestar-vite ``` -------------------------------- ### Create SvelteKit Project Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/sveltekit.rst Command to initialize a new SvelteKit project with Litestar Vite template. ```bash litestar assets init --template sveltekit ``` -------------------------------- ### Generated routes.ts Example Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/type-generation.rst Example of the generated routes.ts file, showing type-safe route handling. ```typescript // If OpenAPI schemas include a `format`, `routes.ts` also emits semantic aliases // and uses them in route parameter types (aliases are plain primitives, no runtime parsing). export type UUID = string; export type DateTime = string; // Generated types export type RouteName = "home" | "dashboard" | "user-profile" | ...; export interface RoutePathParams { "user-profile": { userId: number }; "home": Record; // ... } export interface RouteQueryParams { "user-profile": Record; "home": Record; // ... } type EmptyParams = Record type MergeParams = A extends EmptyParams ? (B extends EmptyParams ? EmptyParams : B) : B extends EmptyParams ? A : A & B; export type RouteParams = MergeParams; // Type-safe route function (params required only when needed) export function route(name: T): string; export function route(name: T, params?: RouteParams): string; export function route(name: T, params: RouteParams): string; // Usage route("home"); // "/" route("user-profile", { userId: 123 }); // "/users/123" route("user-profile"); // TS Error: missing params ``` -------------------------------- ### Implement Books Grid Source: https://github.com/litestar-org/litestar-vite/blob/main/examples/README.md Responsive grid layout for listing multiple books. ```html

{title}

{author} • {year}

{tags}

``` -------------------------------- ### Initialize Litestar Vite application Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/PYPI_README.md Configure the VitePlugin within a Litestar application instance. ```python import os from pathlib import Path from litestar import Litestar from litestar_vite import PathConfig, ViteConfig, VitePlugin DEV_MODE = os.getenv("VITE_DEV_MODE", "true").lower() in ("true", "1", "yes") app = Litestar( plugins=[VitePlugin(config=ViteConfig( dev_mode=DEV_MODE, paths=PathConfig(root=Path(__file__).parent), ))] ) ``` -------------------------------- ### Type Generation Import Example Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/sveltekit.rst Example of importing generated TypeScript types in a SvelteKit application. ```typescript import type { User } from '$lib/generated/types.gen' import { route } from '$lib/generated/routes' ``` -------------------------------- ### Initialize Astro Project Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/astro.rst Command to create a new Astro project with Litestar Vite integration. ```bash litestar assets init --template astro ``` -------------------------------- ### Configure Litestar Application with Vite Source: https://github.com/litestar-org/litestar-vite/blob/main/examples/README.md Sets up the Litestar application with the Vite plugin and required path configuration. ```python from litestar import Litestar from litestar_vite import ViteConfig, VitePlugin, PathConfig vite = VitePlugin(config=ViteConfig( dev_mode=DEV_MODE, paths=PathConfig(root=here), )) app = Litestar( route_handlers=[LibraryController], plugins=[vite], debug=True, ) ``` -------------------------------- ### Generated inertia-pages.json Example Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/type-generation.rst Example of the generated inertia-pages.json file, used by the Vite plugin to generate page-props.ts. ```json { "pages": { "Dashboard": { "route": "/dashboard", "tsType": "DashboardProps", "schemaRef": "#/components/schemas/DashboardProps", "customTypes": ["DashboardProps"] } }, "typeImportPaths": { "InternalProps": "@/types/internal" }, "fallbackType": "unknown", "typeGenConfig": { "includeDefaultAuth": true, "includeDefaultFlash": true }, "generatedAt": "2025-12-11T00:00:00Z" } ``` -------------------------------- ### Example Rate Limiting Approach Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/precognition.rst An example of how to implement rate limiting for Precognition requests in Litestar. ```python from litestar.middleware.rate_limit import RateLimitConfig # You could check for Precognition header in a custom rate limiter # to apply different limits for validation vs. submission requests ``` -------------------------------- ### Enable Global route() Registration Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/routing.rst Configure the Litestar Vite backend to expose the route() helper globally on the window object. ```python from litestar_vite.config import TypeGenConfig ViteConfig( types=TypeGenConfig( global_route=True, # Register route() on window ), ); ``` -------------------------------- ### Project Structure Example Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/astro.rst Illustrates the typical file and directory structure of an Astro project integrated with Litestar. ```text my-app/ ├── app.py # Litestar backend ├── package.json ├── astro.config.mjs # Astro configuration with Litestar integration ├── tsconfig.json └── src/ ├── pages/ │ └── index.astro # Pages (file-based routing) ├── components/ │ └── Card.astro # Astro components └── generated/ # Generated types from OpenAPI ``` -------------------------------- ### JSON Templating Example Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/htmx.rst Example of using Litestar HTMX extension for client-side JSON templating. ```html+jinja
``` -------------------------------- ### Configure Framework Mode in Litestar Source: https://github.com/litestar-org/litestar-vite/blob/main/llms-full.txt Sets up Vite for framework-specific modes like Astro, Nuxt, or SvelteKit. ```python from litestar import Litestar from litestar_vite import VitePlugin, ViteConfig app = Litestar( plugins=[ VitePlugin(config=ViteConfig( mode="framework", dev_mode=True, )) ], ) ``` -------------------------------- ### Project Structure Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/usage/vite.rst The generated project structure after initialization. ```text my_project/ ├── public/ # Compiled assets ├── src/ # Frontend source (default for non-Inertia) ├── resources/ # Frontend source (Inertia templates only) ├── package.json # Node.js dependencies ├── vite.config.js # Vite configuration └── pyproject.toml # Python dependencies ``` -------------------------------- ### Interactive Island Component (React Example) Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/astro.rst Example of an interactive island component written in React, demonstrating client-side logic and API calls. ```tsx // src/components/Counter.tsx (React, Vue, Svelte, etc.) import { useState } from 'react' import { route } from '../generated/routes' export default function Counter() { const [count, setCount] = useState(0) const [summary, setSummary] = useState(null) async function loadSummary() { const res = await fetch(route('summary')) setSummary(await res.json()) } return (
{summary &&

{summary.headline}

}
) } ``` -------------------------------- ### litestar(config: string | string[] | PluginConfig) Source: https://github.com/litestar-org/litestar-vite/blob/main/llms-full.txt Initializes the Litestar Vite plugin. Accepts either a string/array of input paths or a full PluginConfig object. ```APIDOC ## litestar(config) ### Description Initializes the Litestar Vite plugin. Returns a plugin array configured for the project. ### Parameters - **config** (string | string[] | PluginConfig) - Required - The input paths or configuration object for the plugin. ``` -------------------------------- ### Error Bags Example Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/error-handling.rst This Python example demonstrates the use of error bags in Inertia. It shows how the `error()` helper respects the `X-Inertia-Error-Bag` header sent by the client to scope errors to specific bags. The example includes setting an error for the 'email' field within a specific bag. ```python # Errors are scoped by the X-Inertia-Error-Bag header sent by the client # The error() helper automatically respects the error bag from the request @post("/profile") async def update_profile(request: Request) -> InertiaBack: data = await request.json() # Error bag is extracted from X-Inertia-Error-Bag header error_bag = request.headers.get("X-Inertia-Error-Bag") if not data.get("email"): error(request, "email", "Email is required") return InertiaBack(request) # Errors are scoped to the error bag on the frontend return InertiaRedirect(request, "/profile") ``` -------------------------------- ### Create React Project Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/react.rst Command to initialize a new React project with TypeScript support. ```bash litestar assets init --template react ``` -------------------------------- ### Main Container Wrapper Source: https://github.com/litestar-org/litestar-vite/blob/main/examples/README.md Standard container for wrapping application content. ```html
``` -------------------------------- ### Flash Messages Example Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/error-handling.rst This Python example shows how to use the `flash()` helper to send success or informational notifications in Litestar for Inertia applications. It demonstrates flashing a success message after a user is created and returning an `InertiaRedirect`. ```python from litestar_vite.inertia import flash @post("/users") async def create_user(request: Request, data: UserCreate) -> InertiaRedirect: user = await User.create(**data.dict()) flash(request, "User created successfully!", "success") return InertiaRedirect(request, f"/users/{user.id}") ``` -------------------------------- ### Pydantic Validation Example Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/error-handling.rst This Python example illustrates how Litestar automatically handles Pydantic validation errors and converts them into the `errors` prop format expected by Inertia. It defines a `UserCreate` Pydantic model and shows a route that uses it, where validation errors are implicitly managed. ```python from pydantic import BaseModel, EmailStr class UserCreate(BaseModel): email: EmailStr name: str @post("/users") async def create_user(data: UserCreate) -> InertiaRedirect: # Pydantic validation errors are automatically caught user = await User.create(**data.dict()) return InertiaRedirect(request, f"/users/{user.id}") ``` -------------------------------- ### Example JSON Payload Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/templates.rst The structure of the JSON payload used for the data-page attribute. ```json { "component": "Dashboard", "props": {"user": {"name": "Alice"}}, "url": "/dashboard", "version": "abc123" } ``` -------------------------------- ### Scaffold a complete Inertia project Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/installation.rst Scaffold a complete Inertia project using litestar assets init. ```bash litestar assets init --template react-inertia litestar assets init --template vue-inertia litestar assets init --template svelte-inertia ``` -------------------------------- ### Using the defer helper Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/deferred-props.rst Use the defer helper to mark specific props for asynchronous loading after the initial page render. ```python from typing import Any from litestar import get from litestar_vite.inertia import defer @get("/dashboard", component="Dashboard") async def dashboard() -> dict[str, Any]: return { "user": get_current_user(), # Immediate "stats": defer("stats", get_dashboard_stats), # Deferred "chart": defer("chart", get_chart_data), # Deferred } ``` -------------------------------- ### InertiaRedirect Example Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/redirects.rst Redirect within your application (same-origin). ```python from litestar import post from litestar.request import Request from litestar_vite.inertia import InertiaRedirect @post("/logout") async def logout(request: Request) -> InertiaRedirect: request.session.clear() return InertiaRedirect(request, "/login") @post("/users") async def create_user(request: Request, data: UserCreate) -> InertiaRedirect: user = await User.create(**data.dict()) return InertiaRedirect(request, f"/users/{user.id}") ``` -------------------------------- ### Export routes via CLI Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/usage/types.rst Command to export route metadata separately. ```bash litestar assets export-routes ``` -------------------------------- ### Production Build and Serve Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/astro.rst Commands for building the Astro site for production and serving it with Litestar. ```bash # 1. Build Astro: litestar assets build # 2. Serve the built site: # Static mode (default): VITE_DEV_MODE=false litestar run (Litestar serves dist/) ``` -------------------------------- ### Project File Structure Source: https://github.com/litestar-org/litestar-vite/blob/main/examples/README.md Standard directory layout for Litestar-Vite projects. ```text examples/{example-name}/ ├── app.py # Litestar application with LibraryController ├── package.json # NPM dependencies ├── vite.config.ts # Vite configuration with Tailwind ├── tsconfig.json # TypeScript configuration ├── src/ # Frontend source (structure varies by framework) │ ├── app.css # Tailwind imports │ └── ... └── .gitignore ``` -------------------------------- ### Vite Configuration Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/svelte.rst Example Vite configuration for a Svelte application. ```typescript import { defineConfig } from "vite"; import { litestar } from "@litestar/vite"; export default defineConfig({ plugins: [ litestar({ // The plugin auto-reads assetUrl, bundleDir from .litestar.json (generated by Python) }), ], build: { // Vite serves the index.html directly in SPA mode // The plugin will automatically set the correct resourceDir // and output directory based on the .litestar.json file }, }); ``` -------------------------------- ### Configure Template/HTMX Mode in Litestar Source: https://github.com/litestar-org/litestar-vite/blob/main/llms-full.txt Sets up Vite for template-based rendering with Jinja2 and HTMX. ```python from litestar import Litestar from litestar.plugins.jinja import JinjaTemplateEngine from litestar.template.config import TemplateConfig from litestar_vite import VitePlugin, ViteConfig app = Litestar( plugins=[VitePlugin(config=ViteConfig(mode="template", dev_mode=True))], template_config=TemplateConfig(engine=JinjaTemplateEngine, directory="templates"), ) ``` ```html {{ vite_hmr() }} {{ vite("src/main.ts") }} ``` -------------------------------- ### Build assets with the Litestar CLI Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/usage/production.rst This command bundles and optimizes all assets, generates a manifest file, and outputs the files to the configured `bundle_dir`. ```bash litestar assets build ``` -------------------------------- ### Runtime Configuration Example Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/nuxt.rst Accessing runtime configuration in Nuxt for API proxy and prefix. ```typescript // In composables or pages const config = useRuntimeConfig() const apiUrl = config.public.apiProxy // http://localhost:8000 const apiPrefix = config.public.apiPrefix // /api ``` -------------------------------- ### Usage with Inertia.js Forms Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/usage/types.rst Example of using generated schema types with Inertia.js React forms. ```text import { useForm } from '@inertiajs/react' import type { FormInput, SuccessResponse } from '@/generated/schemas' import { route } from '@/generated/routes' ``` -------------------------------- ### Configure vite.config.js Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/usage/vite.rst Create the Vite configuration file to include the Litestar plugin. ```javascript import { defineConfig } from 'vite' import litestar from 'litestar-vite-plugin' export default defineConfig({ plugins: [ litestar({ input: ['src/main.ts'], }) ] }) // For Inertia templates, use resources/main.ts instead ``` -------------------------------- ### Vite Configuration Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/react.rst Example Vite configuration file for Litestar integration. ```typescript import { defineConfig } from "vite"; import litestar from "vite-plugin-litestar"; export default defineConfig({ plugins: [litestar()], build: { outDir: "./.vite/build", manifest: true, sourcemap: true, }, server: { port: 3000, }, }); ``` -------------------------------- ### Enable Inertia with defaults Source: https://github.com/litestar-org/litestar-vite/blob/main/docs/frameworks/inertia/configuration.rst Use the inertia parameter in ViteConfig to enable Inertia integration with default settings. ```python from litestar_vite import ViteConfig, VitePlugin VitePlugin(config=ViteConfig( dev_mode=True, inertia=True, # Shortcut - enables with all defaults )) ```