### Complete Inertia Configuration Example Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-define-config.md This example demonstrates a comprehensive Inertia configuration, including custom assets version, history encryption, and Server-Side Rendering (SSR) settings with conditional page rendering. ```typescript // config/inertia.ts import { defineConfig } from '@adonisjs/inertia' import type { HttpContext } from '@adonisjs/core/http' export default defineConfig({ rootView: 'layouts/app', assetsVersion: '1.0.0', encryptHistory: true, ssr: { enabled: true, entrypoint: 'inertia/ssr.tsx', bundle: 'build/ssr/ssr.js', pages: (ctx: HttpContext, page: string) => { // Selectively enable SSR for specific pages return !page.includes('admin') } } }) ``` -------------------------------- ### Complete Root Layout Example with Edge Tags Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-edge-plugin.md This example demonstrates a complete HTML layout using both @inertiaHead for SSR head tags and @inertia for the root element, along with Vite asset linking. ```edge My App {{-- Render SSR head tags --}} @inertiaHead(page) {{-- Link to Vite-generated assets --}} @vite('resources/js/app.ts') {{-- Render Inertia root element --}} @inertia(page, { id: 'app', class: 'min-h-screen bg-gray-50' }) ``` -------------------------------- ### InertiaProvider boot() Method Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia-provider.md Completes the Inertia setup by registering the Edge plugin and route macros. It calls registerEdgePlugin() and adds the renderInertia macro to BriskRoute. ```typescript async boot(): Promise ``` -------------------------------- ### Full Server-Side Rendering (SSR) Setup Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/configuration.md Enables full SSR with history encryption. Ensure the entrypoint and bundle paths are correctly configured. ```typescript export default defineConfig({ rootView: 'app', encryptHistory: true, ssr: { enabled: true, entrypoint: 'inertia/ssr.tsx', bundle: 'build/ssr/ssr.js' } }) ``` -------------------------------- ### Basic Inertia Configuration Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/configuration.md Initialize Inertia configuration with the default options. This is sufficient for a basic setup. ```typescript // config/inertia.ts import { defineConfig } from '@adonisjs/inertia' export default defineConfig({ // Configuration options go here }) ``` -------------------------------- ### Resolve Page Component Examples Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-client-helpers.md Demonstrates how to use `resolvePageComponent` for single path resolution, multiple path resolution with fallbacks, and with layout assignment. ```typescript // Single path resolution const component = await resolvePageComponent('Home', { 'Home': () => import('./pages/Home.vue'), 'About': () => import('./pages/About.vue') }) // Multiple path resolution (fallback) const component = await resolvePageComponent(['Dashboard/Admin', 'Dashboard'], { 'Dashboard': () => import('./pages/Dashboard.vue') }) // With layout assignment const component = await resolvePageComponent('Home', { 'Home': () => import('./pages/Home.vue') }, AppLayout) ``` -------------------------------- ### Example Vue 3 Page Component Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-index-pages.md A basic Vue 3 component example demonstrating the use of `defineProps` to declare component properties. This serves as a basis for type extraction. ```vue ``` -------------------------------- ### Vite Configuration Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/QUICK-REFERENCE.md Provides an example of how to configure Vite for Server-Side Rendering (SSR) with AdonisJS Inertia. ```APIDOC ## Vite Configuration ### Description Configure Vite to enable Server-Side Rendering (SSR) for your Inertia application. ### Configuration (`vite.config.ts`) ```typescript import { defineConfig } from 'vite' import inertia from '@adonisjs/inertia/vite' export default defineConfig({ plugins: [ inertia({ ssr: { enabled: true, entrypoint: 'inertia/ssr.tsx', output: 'build/ssr' } }) ] }) ``` ``` -------------------------------- ### Full Inertia Route File Example Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia-provider.md Demonstrates multiple Inertia page renderings within a route file, including a grouped route with authentication middleware. ```typescript // routes/web.ts import router from '@adonisjs/core/services/router' router.get('/', [].renderInertia('Home', { welcome: 'Hello World' })) router.get('/about', [].renderInertia('About', { team: teamMembers })) router.group(() => { router.get('/dashboard', [].renderInertia('Dashboard', { stats: dashboardStats })) router.get('/profile', [].renderInertia('Profile', { user: currentUser })) }).middleware('auth') ``` -------------------------------- ### Example React Page Component Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-index-pages.md A React functional component named 'Home' that accepts 'title' and 'description' props. This example illustrates how props are defined and used in a React component for type generation. ```typescript interface Props { title: string description: string } export default function Home({ title, description }: Props) { return

{title}: {description}

} ``` -------------------------------- ### Default Configuration with Root View Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/configuration.md When omitting configuration options, defaults are applied. This example shows setting only the root view. ```typescript // Input export default defineConfig({ rootView: 'app' }) // Applied configuration { rootView: 'app', encryptHistory: false, ssr: { enabled: false, bundle: 'ssr/ssr.js', entrypoint: 'inertia/ssr.tsx' } } ``` -------------------------------- ### InertiaManager Injection Example Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia-provider.md Demonstrates how to inject the InertiaManager into your application using the IoC container after it has been registered by the InertiaProvider. ```typescript // InertiaManager is automatically available for injection const inertiaManager = await app.container.make(InertiaManager) ``` -------------------------------- ### Inertia Configuration Example Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/QUICK-REFERENCE.md Configure the Inertia integration by specifying the root Edge view, assets version, history encryption, and Server-Side Rendering (SSR) options. ```typescript import { defineConfig } from '@adonisjs/inertia' export default defineConfig({ rootView: 'app', // Edge template assetsVersion: undefined, // Auto-detect encryptHistory: false, // Browser history ssr: { enabled: false, // SSR enabled entrypoint: 'inertia/ssr.tsx', // Dev entry point bundle: 'build/ssr/ssr.js', // Prod bundle pages: ['Home', 'About'] // Pages to SSR } }) ``` -------------------------------- ### Example Usage of optional() function Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-symbols.md Demonstrates how to use the `optional()` function to mark a prop that is optional and only included when explicitly requested. ```typescript const rareProp = optional(() => computeExpensiveData()) // Object contains [OPTIONAL_PROP]: true ``` -------------------------------- ### Get Asset Version Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/QUICK-REFERENCE.md Shows how to retrieve the current asset version used by Inertia. ```APIDOC ## Get Asset Version ### Description Retrieve the current asset version. This is typically used for cache-busting assets. ### Usage ```typescript const version = ctx.inertia.getVersion() ``` ``` -------------------------------- ### Inertia Configuration Validation Example (Correct) Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/configuration.md Demonstrates the correct way to define Inertia configuration using `defineConfig`. TypeScript validation ensures type safety and prevents invalid option names at build time. ```typescript // ✅ Correct export default defineConfig({ encryptHistory: true }) ``` -------------------------------- ### Test API Client Responses Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/QUICK-REFERENCE.md Examples for testing API client responses, including checking for Inertia headers and performing partial data requests. ```typescript // Test with API client client.get('/dashboard').expect(200) // Test Inertia response const response = client.get('/dashboard') expect(response.headers['x-inertia']).toBe('true') // Test partial request client.get('/dashboard') .header('x-inertia-partial-component', 'Dashboard') .header('x-inertia-partial-data', 'stats') ``` -------------------------------- ### SSR Entrypoint Example Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-server-renderer.md Define the default export function for the SSR entrypoint. This function receives the page object and must return an object with 'head' and 'body' properties. ```typescript // inertia/ssr.tsx import { renderToString } from 'react-dom/server' import { createMemoryHistory } from '@inertiajs/react' export default async (page: PageObject) => { const html = renderToString() return { head: ['Page Title'], body: html } } ``` -------------------------------- ### Usage in React Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-client-helpers.md Shows how to integrate `resolvePageComponent` within a React application's Inertia setup, using `import.meta.glob` for page discovery. ```typescript import { usePage } from '@inertiajs/react' import { resolvePageComponent } from '@adonisjs/inertia/helpers' const pages = import.meta.glob('./pages/**/*.tsx', { eager: true }) export function createApp() { return { resolve: (name) => resolvePageComponent(name, pages), } } ``` -------------------------------- ### Example Usage of always() function Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-symbols.md Demonstrates how to use the `always()` function to mark a prop that should always be included in responses. ```typescript const criticalData = always({ id: 1, name: 'Important' }) // Object contains [ALWAYS_PROP]: true ``` -------------------------------- ### Encrypt History Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/QUICK-REFERENCE.md Provides an example of how to enable or disable history encryption for Inertia. ```APIDOC ## Encrypt History ### Description Enable or disable the encryption of the browser's history. When enabled, history entries will be encrypted. ### Usage ```typescript inertia.encryptHistory(true) ``` ``` -------------------------------- ### Full Inertia Middleware Implementation Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia-middleware.md A complete example of a custom Inertia middleware class that extends BaseInertiaMiddleware and implements the share method to provide user, flash messages, and validation errors to Inertia pages. ```typescript import BaseInertiaMiddleware from '@adonisjs/inertia/inertia_middleware' import type { HttpContext } from '@adonisjs/core/http' export default class InertiaMiddleware extends BaseInertiaMiddleware { async share(ctx: HttpContext) { return { user: ctx.auth?.user || null, flash: ctx.session?.flashMessages.all(), errors: this.getValidationErrors(ctx) } } } ``` -------------------------------- ### Inertia Middleware Setup Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/QUICK-REFERENCE.md Configure the Inertia middleware to share common data across all Inertia requests. This includes user authentication status, flash messages, and validation errors. ```typescript import BaseInertiaMiddleware from '@adonisjs/inertia/inertia_middleware' export default class InertiaMiddleware extends BaseInertiaMiddleware { async share(ctx) { return { user: ctx.auth?.user, flash: ctx.session?.flashMessages.all(), errors: this.getValidationErrors(ctx) } } } ``` -------------------------------- ### Define Inertia Configuration Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-define-config.md Configure Inertia.js by defining the root view and Server-Side Rendering (SSR) options. This setup is typically placed in `config/inertia.ts` and loaded by the InertiaProvider. ```typescript // config/inertia.ts import { defineConfig } from '@adonisjs/inertia' export default defineConfig({ rootView: 'inertia_layout', ssr: { enabled: process.env.NODE_ENV === 'production', entrypoint: 'inertia/ssr.tsx', bundle: 'build/ssr/ssr.js' } }) ``` -------------------------------- ### Selective Server-Side Rendering (SSR) Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/configuration.md Configures SSR to be enabled conditionally based on the context and page. This example enables SSR for pages not containing 'Admin' and when a user is authenticated. ```typescript export default defineConfig({ rootView: 'app', ssr: { enabled: true, pages: (ctx, page) => { return !page.includes('Admin') && !!ctx.auth?.user } } }) ``` -------------------------------- ### Configure SSR Selective Rendering Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/QUICK-REFERENCE.md Enable Server-Side Rendering (SSR) and define a custom `pages` function to control which pages are SSR'd. This example SSRs public pages only. ```typescript ssr: { enabled: true, pages: (ctx, page) => { // SSR public pages only return !page.includes('Admin') && !page.includes('Private') } } ``` -------------------------------- ### Disabling Automatic Provider Registration Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia-provider.md The Inertia provider is registered automatically upon installation. To disable this behavior, remove it from the `providers` array in `adonisrc.ts` or from the installed packages. ```typescript import { defineConfig } from '@adonisjs/core/hash' export default defineConfig({ providers: [ // ... other providers // '@adonisjs/inertia' is included by default ] }) ``` -------------------------------- ### Client Build Output Structure Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-vite-plugin.md Illustrates the directory structure for client assets after a build without SSR. ```bash build/public/assets/ ├── app.js ├── app.css └── manifest.json ``` -------------------------------- ### init() Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia-middleware.md Initializes the Inertia instance for the current request, making it available on the HTTP context. ```APIDOC ### init() Initialize the Inertia instance for the current request. ```typescript async init(ctx: HttpContext): void ``` This method creates an Inertia instance and attaches it to the HTTP context, making it available throughout the request lifecycle. #### Parameters - **ctx** (HttpContext) - Required - The HTTP context object **Example:** ```typescript await middleware.init(ctx) // ctx.inertia is now available ``` ``` -------------------------------- ### SSR Build Output Structure Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-vite-plugin.md Illustrates the directory structure for assets when SSR is enabled, including both client assets and the SSR bundle. ```bash build/public/assets/ ├── app.js ├── app.css └── manifest.json build/ssr/ ├── ssr.js └── ... ``` -------------------------------- ### Get Asset Version Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/QUICK-REFERENCE.md Retrieves the current asset version used by Inertia for cache busting. ```typescript const version = ctx.inertia.getVersion() ``` -------------------------------- ### ServerRenderer Constructor Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-server-renderer.md Initializes a new instance of the ServerRenderer. It requires configuration and a Vite instance for rendering. ```APIDOC ## Constructor ServerRenderer ### Description Creates a new ServerRenderer instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature ```typescript constructor(config: InertiaConfig, vite: Vite) ``` ### Parameters - **config** (InertiaConfig) - Required - Inertia configuration object containing SSR settings - **vite** (Vite) - Required - Vite instance for development mode rendering and asset management ### Request Example ```typescript const renderer = new ServerRenderer(config, vite) ``` ``` -------------------------------- ### BaseInertiaMiddleware Constructor Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia-middleware.md The constructor for BaseInertiaMiddleware. It does not accept any parameters. Users should extend this class and implement the `share` method. ```APIDOC ## Constructor ```typescript constructor() ``` No constructor parameters. Extend this class and implement the `share` method in your application. ``` -------------------------------- ### Instantiate ServerRenderer Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-server-renderer.md Create a new instance of the ServerRenderer. Requires Inertia configuration and a Vite instance. ```typescript const renderer = new ServerRenderer(config, vite) ``` -------------------------------- ### Configure SSR Entrypoint Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/configuration.md Specify the path to the SSR entry point file used during development. Vite's runtime API loads this file to render pages on the server. The entry point must export an async function that returns head and body content. ```typescript // inertia/ssr.tsx import { renderToString } from 'react-dom/server' import App from './app' export default async (page) => { const body = renderToString() return { head: ['Page Title'], body } } ``` -------------------------------- ### Import Core Classes and Types Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/QUICK-REFERENCE.md Import the main Inertia class, manager, renderer, middleware, and configuration utilities. ```typescript import { Inertia } from '@adonisjs/inertia' import { InertiaManager, ServerRenderer } from '@adonisjs/inertia' import BaseInertiaMiddleware from '@adonisjs/inertia/inertia_middleware' import { defineConfig } from '@adonisjs/inertia' ``` -------------------------------- ### ResolvableOf Utility Type Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/types.md Represents a resource item, collection, or paginator that can be resolved to get normalized objects. It defines a `resolve` method for this purpose. ```typescript type ResolvableOf = { resolve(container: ContainerResolver, depth: number, maxDepth?: number): Promise } ``` -------------------------------- ### Build Production Assets Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/configuration.md Commands to run for building production assets. Ensure SSR bundle is built if enabled and assets are versioned. ```bash npm run build ``` ```bash NODE_ENV=production npm run build ``` -------------------------------- ### Configure SSR Entrypoint Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-define-config.md Specify the path to the SSR entry point file, used in development with Vite's runtime API. Ensure this path is correct for your project structure. ```typescript defineConfig({ ssr: { enabled: true, entrypoint: 'resources/ssr.tsx' } }) ``` -------------------------------- ### Get Inertia Request Information Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia.md Extract Inertia-specific details from request headers, such as whether it's an Inertia or partial request. Optionally recompute the information. ```typescript const info = inertia.requestInfo() if (info.isInertiaRequest) { // Handle as Inertia request } if (info.isPartialRequest) { // Handle partial data request } ``` -------------------------------- ### Instantiate Inertia Class Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia.md Create a new Inertia instance by passing the HTTP context, configuration, and optional Vite and server renderer instances. ```typescript const inertia = new Inertia(ctx, { rootView: 'app', ssr: { enabled: true } }, vite, serverRenderer) ``` -------------------------------- ### Get Asset Version Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia.md Retrieves the computed version string for asset cache busting. It uses the Vite manifest hash if available, otherwise defaults to '1'. ```typescript getVersion(): string ``` ```typescript const version = inertia.getVersion() // Returns MD5 hash of Vite manifest or '1' if not available ``` -------------------------------- ### Inertia Configuration for SSR Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-server-renderer.md Enable SSR and specify the entrypoint for development and the bundle path for production within the Inertia configuration object. ```typescript const config = { ssr: { enabled: true, entrypoint: 'inertia/ssr.tsx', // Entry point file for development bundle: 'build/ssr/ssr.js' // Pre-built bundle for production } } ``` -------------------------------- ### render() Method Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-server-renderer.md Renders an Inertia page on the server. It utilizes Vite's Runtime API in development and pre-built SSR bundles in production. ```APIDOC ## render() ### Description Render an Inertia page on the server. In development mode, uses Vite's Runtime API to execute the SSR entrypoint. In production mode, imports and uses the pre-built SSR bundle. ### Method Signature ```typescript async render(pageObject: PageObject): Promise<{ head: string[]; body: string }> ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **pageObject** (PageObject) - Required - The Inertia page object containing component, props, and metadata ### Response #### Success Response (200) - **head** (string[]) - Array of HTML strings to be inserted in the `` tag. - **body** (string) - HTML string to be rendered in the page body. ### Request Example ```typescript const pageObject = { component: 'Home', props: { user: { name: 'John' } }, url: '/dashboard', version: '1.0.0' } const { head, body } = await renderer.render(pageObject) // head: ['', ...other head tags...] // body: '
...rendered HTML...
' ``` ``` -------------------------------- ### Import Vite and Edge Plugins Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/QUICK-REFERENCE.md Import the Vite plugin for asset management and the Edge plugin for integrating Inertia with the Edge templating engine. ```typescript import inertia from '@adonisjs/inertia/vite' import { edgePluginInertia } from '@adonisjs/inertia/plugins/edge' ``` -------------------------------- ### Import Client and Page Helpers Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/QUICK-REFERENCE.md Import client-side helpers for resolving page components and utilities for indexing pages. ```typescript import { resolvePageComponent } from '@adonisjs/inertia/helpers' import { indexPages } from '@adonisjs/inertia' ``` -------------------------------- ### Inertia Page Rendering via Route Macro Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/QUICK-REFERENCE.md Render an Inertia page directly within a route definition using a custom macro. This simplifies route setup for Inertia views. ```typescript router.get('/', [].renderInertia('Home', { data: 'value' })) ``` -------------------------------- ### Share Data Globally Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/QUICK-REFERENCE.md Demonstrates how to share data globally with Inertia, either within middleware or by chaining share calls. ```APIDOC ## Share Data Globally ### Description Share data globally with Inertia. This data will be available in all your Inertia responses. ### Usage **In middleware:** ```typescript return { user: ctx.auth?.user, flash: ctx.session?.flashMessages.all() } ``` **Or chain share calls:** ```typescript ctx.inertia .share({ user: ctx.auth?.user }) .share({ permissions: userPermissions }) ``` ``` -------------------------------- ### getVersion() Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia.md Computes and caches the assets version for cache busting. Uses Vite manifest hash when available, otherwise defaults to '1'. ```APIDOC ## getVersion() ### Description Compute and cache the assets version for cache busting. Uses Vite manifest hash when available, otherwise defaults to '1'. ### Returns - string: The computed version string for asset versioning. ### Example ```typescript const version = inertia.getVersion() // Returns MD5 hash of Vite manifest or '1' if not available ``` ``` -------------------------------- ### Redirect Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/QUICK-REFERENCE.md Shows how to perform a client-side redirect using Inertia and setting the response status. ```APIDOC ## Redirect ### Description Perform a client-side redirect to a new location and optionally set the HTTP response status. ### Usage ```typescript inertia.location('/dashboard') ctx.response.status(409) ``` ``` -------------------------------- ### Build props for standard Inertia visits Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-props.md Use `buildStandardVisitProps` to construct props for regular Inertia page loads. It handles deferred and mergeable props. ```typescript async function buildStandardVisitProps( pageProps: PageProps, containerResolver: ContainerResolver ): Promise<{ props: ComponentProps mergeProps: string[] deepMergeProps: string[] deferredProps: { [group: string]: string[] } }> ``` ```typescript const result = await buildStandardVisitProps({ user: { name: 'John' }, posts: defer(() => getPosts()), settings: merge({ theme: 'dark' }) }) // Returns: { // props: { user: {...} }, // deferredProps: { default: ['posts'] }, // mergeProps: ['settings'], // deepMergeProps: [] // } ``` -------------------------------- ### Basic Vite Configuration with Inertia Plugin Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-vite-plugin.md Configure Vite to use the Inertia plugin with default settings. This is the simplest way to integrate Inertia.js with Vite. ```typescript import { defineConfig } from 'vite' import inertia from '@adonisjs/inertia/vite' export default defineConfig({ plugins: [inertia()] }) ``` -------------------------------- ### share() Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia-middleware.md An abstract method to share data with all Inertia pages. Implement this in your custom middleware class to provide global props. ```APIDOC ### share() Share data with all Inertia pages. ```typescript abstract share?(ctx: HttpContext): PageProps | Promise ``` This method should return an object containing data that will be available to all Inertia pages as props. Implement this in your middleware class. #### Parameters - **ctx** (HttpContext) - Required - The HTTP context object **Returns:** Props to share across all pages or Promise resolving to props. **Example:** ```typescript class InertiaMiddleware extends BaseInertiaMiddleware { async share(ctx: HttpContext) { return { user: ctx.auth?.user, flash: ctx.session?.flashMessages.all(), errors: this.getValidationErrors(ctx) } } } ``` ``` -------------------------------- ### Configure Dynamic Root View Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-define-config.md Dynamically select the root Edge template based on the HTTP context. This allows for conditional rendering of different layouts. ```typescript defineConfig({ rootView: (ctx) => { return ctx.auth?.user?.isAdmin ? 'admin/layout' : 'app' } }) ``` -------------------------------- ### Inertia Constructor Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia.md Creates a new Inertia instance for handling requests. It requires the HTTP context and Inertia configuration, with optional parameters for Vite and a server-side renderer. ```APIDOC ## Constructor ```typescript constructor( ctx: HttpContext, config: InertiaConfig, vite?: Vite, serverRenderer?: ServerRenderer ) ``` Creates a new Inertia instance for handling requests. ### Parameters #### Path Parameters - ctx (HttpContext) - Required - HTTP context for the current request - config (InertiaConfig) - Required - Inertia configuration object - vite (Vite) - Optional - Vite instance for asset management - serverRenderer (ServerRenderer) - Optional - Optional server-side renderer for SSR **Example:** ```typescript const inertia = new Inertia(ctx, { rootView: 'app', ssr: { enabled: true } }, vite, serverRenderer) ``` ``` -------------------------------- ### Configure Specific Pages for SSR Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-define-config.md Cherry-pick which pages should be server-side rendered by providing an array of page names. If undefined, all pages are SSR'd when enabled. ```typescript defineConfig({ ssr: { enabled: true, pages: ['Home', 'About', 'Contact'] } }) ``` -------------------------------- ### Configure SSR Bundle Path Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-define-config.md Set the path to the pre-built SSR bundle, which is used in production environments. This file should contain your server-rendered application code. ```typescript defineConfig({ ssr: { enabled: true, bundle: 'build/ssr/ssr.js' } }) ``` -------------------------------- ### Import Prop Functions and Type Guards Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/QUICK-REFERENCE.md Import utility functions for managing props, including defer, optional, always, merge, and deepMerge, along with their corresponding type guards. ```typescript import { defer, optional, always, merge, deepMerge } from '@adonisjs/inertia' import { isDeferredProp, isOptionalProp, isAlwaysProp, isMergeableProp } from '@adonisjs/inertia' ``` -------------------------------- ### Creating Props with Symbols Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-symbols.md Shows how to use helper functions like `always`, `optional`, `defer`, `merge`, and `deepMerge` to define different types of props for Inertia. These helpers utilize symbols to manage prop inclusion and merging behavior. ```typescript import { defer, optional, always, merge, deepMerge } from '@adonisjs/inertia' const props = { // Always included, can't be filtered out userId: always(123), // Included in standard visits, can be filtered userName: 'John', // Never included in standard visits, only if requested auditLogs: optional(() => fetchAuditLogs()), // Not included, but client knows it exists, can be loaded notifications: defer(() => fetchNotifications()), // Merged instead of replaced tags: merge(['tag1', 'tag2']), // Deep merged instead of replaced config: deepMerge({ theme: 'dark' }) } ``` -------------------------------- ### render() Method Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia.md Render a page using Inertia with automatic handling of Inertia requests, SSR, and client-side rendering. This method supports Inertia requests, initial page loads with SSR, and initial page loads without SSR. ```APIDOC ## render() Render a page using Inertia with automatic handling of Inertia requests, SSR, and client-side rendering. ```typescript async render( page: Page, pageProps: Pages[Page] extends ComponentProps ? AsPageProps> : never, viewProps?: Record ): Promise> ``` This method handles three distinct rendering scenarios: 1. Inertia requests - Returns JSON page object for client-side navigation 2. Initial page loads with SSR - Returns HTML with server-rendered content 3. Initial page loads without SSR - Returns HTML for client-side hydration ### Parameters #### Path Parameters - page (string) - Required - The page component name to render - pageProps (PageProps) - Required - Props to pass to the page component - viewProps (Record) - Optional - Additional props to pass to the root view template **Returns:** Promise resolving to either a PageObject (for Inertia requests) or an HTML string (for initial page loads). **Example:** ```typescript const result = await inertia.render('Profile', { user: getCurrentUser(), posts: defer(() => getUserPosts()) }) ``` ``` -------------------------------- ### share() Method Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia.md Share props across all pages. This method merges provided props with existing shared state, making them available to all pages rendered by this Inertia instance. ```APIDOC ## share() Share props across all pages. ```typescript share(sharedState: PageProps | (() => AsyncOrSync)): this ``` Merges the provided props with existing shared state, making them available to all pages rendered by this Inertia instance. ### Parameters #### Path Parameters - sharedState (PageProps | (() => AsyncOrSync)) - Required - Props to share across all pages or a function that returns props **Returns:** The Inertia instance for method chaining. **Example:** ```typescript inertia .share({ user: getCurrentUser(), flash: getFlashMessages() }) .share({ permissions: userPermissions }) ``` ``` -------------------------------- ### Implement Inertia Share Method Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia-middleware.md Implement this method to return an object containing data that will be available to all Inertia pages as props. This is typically done within a custom middleware class extending BaseInertiaMiddleware. ```typescript abstract share?(ctx: HttpContext): PageProps | Promise ``` ```typescript class InertiaMiddleware extends BaseInertiaMiddleware { async share(ctx: HttpContext) { return { user: ctx.auth?.user, flash: ctx.session?.flashMessages.all(), errors: this.getValidationErrors(ctx) } } } ``` -------------------------------- ### Inertia Configuration Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia-provider.md Configure the root view and SSR settings for the Inertia provider. ```typescript // config/inertia.ts import { defineConfig } from '@adonisjs/inertia' export default defineConfig({ rootView: 'inertia_layout', ssr: { enabled: false } }) ``` -------------------------------- ### Initialize Inertia Instance Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia-middleware.md Creates an Inertia instance and attaches it to the HTTP context, making it available throughout the request lifecycle. This method should be awaited before using Inertia functionalities. ```typescript async init(ctx: HttpContext): void ``` ```typescript await middleware.init(ctx) // ctx.inertia is now available ``` -------------------------------- ### Specifying Props for Partial Data Requests Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia-headers.md Demonstrates how to use the `x-inertia-partial-data` header to specify a comma-separated list of props to include in partial data requests, ensuring only the requested props are returned. ```typescript // Client cherry-picks specific props request.header('x-inertia-partial-data') // 'user,posts' // Parsed into array const onlyProps = request.header('x-inertia-partial-data')?.split(',') // ['user', 'posts'] // Only these props are returned ``` -------------------------------- ### Basic Inertia Page Rendering Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia-provider.md Render an Inertia component with props using the `renderInertia` route macro. ```typescript // routes/web.ts router.get('/dashboard', []).renderInertia('Dashboard', { user: auth.user }) ``` -------------------------------- ### Import Core Inertia Modules Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/README.md Import necessary modules from the '@adonisjs/inertia' package for core functionality and helpers. ```typescript import { Inertia, InertiaManager, ServerRenderer, InertiaHeaders, defineConfig, symbols } from '@adonisjs/inertia' import { defer, optional, always, merge, deepMerge } from '@adonisjs/inertia' import { resolvePageComponent } from '@adonisjs/inertia/helpers' import { edgePluginInertia } from '@adonisjs/inertia/plugins/edge' import inertiaVitePlugin from '@adonisjs/inertia/vite' ``` -------------------------------- ### buildStandardVisitProps Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-props.md Builds props for standard, non-partial Inertia visits. This function prepares props for full page loads. ```APIDOC ## buildStandardVisitProps() ### Description Builds props for standard (non-partial) Inertia visits. ### Signature ```typescript async function buildStandardVisitProps( pageProps: PageProps, containerResolver: ContainerResolver ): Promise<{ props: ComponentProps mergeProps: string[] deepMergeProps: string[] deferredProps: { [group: string]: string[] } }> ``` ```APIDOC ### Example ```typescript const result = await buildStandardVisitProps({ user: { name: 'John' }, posts: defer(() => getPosts()), settings: merge({ theme: 'dark' }) }) // Returns: { // props: { user: {...} }, // deferredProps: { default: ['posts'] }, // mergeProps: ['settings'], // deepMergeProps: [] // } ``` ``` -------------------------------- ### Check Request Info Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/QUICK-REFERENCE.md Explains how to retrieve and check information about the current Inertia request. ```APIDOC ## Check Request Info ### Description Get information about the current Inertia request, such as whether it's an AJAX request, a partial request, or if an error bag is present. ### Usage ```typescript const info = ctx.inertia.requestInfo() if (info.isInertiaRequest) { /* AJAX */ } if (info.isPartialRequest) { /* Partial data */ } if (info.errorBag) { /* Has error bag */ } ``` ``` -------------------------------- ### InertiaProvider register() Method Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia-provider.md Registers the Inertia configuration and manager in the IoC container. Loads configuration, creates an InertiaManager, and registers it as a singleton. ```typescript async register(): Promise ``` -------------------------------- ### SPA with Client-Side Rendering Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/configuration.md Configuration for a Single Page Application (SPA) where rendering is handled entirely on the client-side. ```typescript export default defineConfig({ rootView: 'app', ssr: { enabled: false } }) ``` -------------------------------- ### Edge Templates Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/QUICK-REFERENCE.md Illustrates how to use Inertia directives within Edge templates for rendering the root element and head tags. ```APIDOC ## Edge Templates ### Description Use Edge templating engine with Inertia.js to render the root HTML element and head tags, especially for Server-Side Rendering (SSR). ### Usage ```edge {{-- SSR head tags --}} @inertiaHead(page) {{-- Vite assets --}} @vite('resources/js/app.ts') {{-- Root element --}} @inertia(page, { id: 'app', class: 'min-h-screen' }) ``` **Available Globals:** - `@inertia(page, attributes)`: Renders the root element for your Inertia app. - `@inertiaHead(page)`: Renders head tags generated during SSR. ``` -------------------------------- ### page() Method Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia.md Build a page object with processed props and metadata. This method creates the complete page object sent to the client or used for server-side rendering, handling prop merging, deferred props, and partial request filtering. ```APIDOC ## page() Build a page object with processed props and metadata. ```typescript async page( page: Page, pageProps: Pages[Page] extends ComponentProps ? AsPageProps> : never ): Promise> ``` Creates the complete page object that will be sent to the client or used for server-side rendering. Handles prop merging, deferred props, and partial request filtering. ### Parameters #### Path Parameters - page (string) - Required - The page component name - pageProps (PageProps) - Required - Props to pass to the page component **Returns:** Promise resolving to the complete PageObject. **Example:** ```typescript const pageObject = await inertia.page('Dashboard', { user: { name: 'John' }, posts: defer(() => getPosts()) }) ``` ``` -------------------------------- ### createForRequest() Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia-manager.md Creates a new Inertia instance for a specific HTTP request, configured with the given request context. ```APIDOC ## createForRequest>() Create a new Inertia instance for a specific HTTP request. ### Parameters #### Path Parameters - **ctx** (HttpContext) - Required - HTTP context for the current request ### Returns A new Inertia instance configured for the given request. ### Request Example ```typescript const inertia = manager.createForRequest(ctx) await inertia.render('Home', { user: ctx.auth.user }) ``` ``` -------------------------------- ### Checking and Setting Inertia Request Header Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia-headers.md Demonstrates how to check if an incoming request is from Inertia and how to set the Inertia response header. ```typescript // Check if request is from Inertia const isInertiaRequest = request.header('x-inertia') === 'true' // Set response as Inertia request response.header('x-inertia', 'true') ``` -------------------------------- ### InertiaProvider Constructor Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia-provider.md Creates a new InertiaProvider instance. Requires the AdonisJS application service instance. ```typescript constructor(protected app: ApplicationService) ``` -------------------------------- ### Configure Static Root View Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-define-config.md Set a static Edge template name for the root HTML shell. This is the default way to specify the layout. ```typescript defineConfig({ rootView: 'app' }) ``` -------------------------------- ### Instantiate InertiaManager Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia-manager.md Create a new InertiaManager instance, providing the Inertia configuration and an optional Vite instance for SSR and asset management. ```typescript const manager = new InertiaManager({ rootView: 'app', ssr: { enabled: true } }, vite) ``` -------------------------------- ### inertiaHead() Global Function Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-edge-plugin.md Renders head tags from server-side rendering. It takes the page object which may contain SSR head tags. ```APIDOC ## inertiaHead() ### Description Renders head tags from server-side rendering. It takes the page object which may contain SSR head tags. ### Signature ```typescript inertiaHead(page?: Record): string ``` ### Parameters #### Page Data (`page`) - **page** (Record) - Optional - The page object containing SSR head tags. ### Returns - Concatenated HTML string of head tags. ### Example ```edge @inertiaHead(page) @inertia(page) ``` ### SSR Head Tags When server-side rendering is enabled, `ssrHead` contains an array of HTML strings (meta tags, stylesheets, etc.) that are joined together. When SSR is disabled, this is empty. ``` -------------------------------- ### Vite Configuration with SSR Enabled Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-vite-plugin.md Configure Vite to use the Inertia plugin with server-side rendering (SSR) enabled. Specify the SSR entrypoint and output directory. ```typescript import { defineConfig } from 'vite' import inertia from '@adonisjs/inertia/vite' export default defineConfig({ plugins: [ inertia({ ssr: { enabled: true, entrypoint: 'inertia/ssr.tsx', output: 'build/ssr' } }) ] }) ``` -------------------------------- ### Define a Deferred Prop with defer() Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-props.md Use `defer()` to create props that are not included in standard visits but can be explicitly requested by the client. This is ideal for computationally expensive data that should only load on demand. ```typescript function defer( fn: () => AsyncOrSync, group?: string ): DeferProp ``` ```typescript // Create a deferred prop for expensive user statistics const userStats = defer(() => { return calculateExpensiveUserStats(userId) }) // Use in page props return inertia.render('dashboard', { user: user, stats: userStats // Only loaded when explicitly requested }) // With grouped deferred props const notifications = defer(() => fetchNotifications(), 'notifications') const messages = defer(() => fetchMessages(), 'notifications') ``` -------------------------------- ### Configure indexPages with Custom Source Directory Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-index-pages.md Configure the indexPages hook to use a custom source directory for React Inertia pages, specifying the path to your components. ```typescript indexPages({ framework: 'react', source: 'resources/inertia/pages' }) ``` -------------------------------- ### InertiaManager Constructor Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia-manager.md Creates a new InertiaManager instance with the provided configuration and an optional Vite instance. ```APIDOC ## Constructor Creates a new InertiaManager instance. ### Parameters #### Path Parameters - **config** (InertiaConfig) - Required - Inertia configuration object - **vite** (Vite) - Optional - Optional Vite instance for asset management and SSR ### Request Example ```typescript const manager = new InertiaManager({ rootView: 'app', ssr: { enabled: true } }, vite) ``` ``` -------------------------------- ### RenderInertiaSsrApp Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/types.md This is the function signature for the SSR render method. It should be exported from the SSR entrypoint file to render Inertia pages on the server. ```APIDOC ## RenderInertiaSsrApp ### Description Function signature for the SSR render method that should be exported from the SSR entrypoint file to render Inertia pages on the server. ### Signature ```typescript type RenderInertiaSsrApp = ( page: PageObject ) => Promise<{ head: string[]; body: string }> ``` ``` -------------------------------- ### defer() Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-props.md Creates a deferred prop that is not included in standard visits but can be explicitly requested by the client. Useful for expensive computations. ```APIDOC ## defer() ### Description Creates a deferred prop that is never included in standard visits but must be shared with the client. Deferred props are useful for expensive computations that should only be loaded when specifically requested by the client. ### Signature ```typescript function defer(fn: () => AsyncOrSync, group?: string): DeferProp ``` ### Parameters #### Function Parameter `fn` - **Type**: `() => AsyncOrSync` - **Required**: Yes - **Description**: Function that computes the prop value when requested. #### Function Parameter `group` - **Type**: `string` - **Required**: No - **Default**: 'default' - **Description**: Group name for organizing related deferred props. ### Returns - **Type**: `DeferProp` - **Description**: A deferred prop object with compute and merge capabilities. ### Example ```typescript // Create a deferred prop for expensive user statistics const userStats = defer(() => { return calculateExpensiveUserStats(userId) }) // Use in page props return inertia.render('dashboard', { user: user, stats: userStats // Only loaded when explicitly requested }) // With grouped deferred props const notifications = defer(() => fetchNotifications(), 'notifications') const messages = defer(() => fetchMessages(), 'notifications') ``` ``` -------------------------------- ### Render Page with Deferred Props Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/QUICK-REFERENCE.md Use `defer` to lazily load props for a page. This is useful for computationally expensive data that doesn't need to be available immediately on initial render. ```typescript return inertia.render('Dashboard', { user: getCurrentUser(), stats: defer(() => calculateStats()), notifications: defer(() => fetchNotifications(), 'notifications') }) ``` -------------------------------- ### optional() Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-props.md Creates an optional prop that is not included in standard visits and must be explicitly requested. This is ideal for data that is rarely needed. ```APIDOC ## optional() ### Description Create an optional prop that is never included in standard visits and can only be explicitly requested. Unlike deferred props, optional props are not shared with the client during standard visits. They are ideal for data that is rarely needed. ### Function Signature ```typescript function optional(fn: () => AsyncOrSync): OptionalProp ``` ### Parameters #### Function Parameter - **fn** ( () => AsyncOrSync ) - Required - Function that computes the prop value when requested ### Returns An optional prop object that computes values lazily. ### Example ```typescript // Create an optional prop for detailed audit logs const auditLogs = optional(() => { return fetchDetailedAuditLogs(resourceId) }) // Use in page props return inertia.render('resource/show', { resource: resource, auditLogs: auditLogs // Only loaded when explicitly requested }) ``` ``` -------------------------------- ### Configure SSR Production Bundle Path Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/configuration.md Set the path to the pre-built SSR bundle used in production. This is the compiled output from your SSR entry point and should be a relative path from the server root or an absolute path. ```typescript export default defineConfig({ ssr: { enabled: true, bundle: 'build/ssr/ssr.js' } }) ``` -------------------------------- ### Create Inertia Instance for Request Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-inertia-manager.md Generate a new Inertia instance tailored for a specific HTTP request context. This instance is then used to render Inertia pages. ```typescript const inertia = manager.createForRequest(ctx) await inertia.render('Home', { user: ctx.auth.user }) ``` -------------------------------- ### Minimal Inertia Configuration Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/api-reference-define-config.md This is the minimum required configuration for Inertia. It overrides the default rootView and uses all other defaults. ```typescript // config/inertia.ts import { defineConfig } from '@adonisjs/inertia' export default defineConfig({ rootView: 'app' }) ``` -------------------------------- ### Minimal Inertia Configuration Source: https://github.com/adonisjs/inertia/blob/4.x/_autodocs/configuration.md Configure the root view for Inertia. All other settings will use their default values. ```typescript export default defineConfig({ rootView: 'app' }) ```