Inertia.js

repository·3.x·Indexed 11 days ago

https://github.com/inertiajs/inertia

A communication layer that bridges backend frameworks and modern frontend libraries like React, Vue, and Svelte. It enables the creation of single-page applications (SPAs) using standard server-side routing and controllers instead of a dedicated REST or GraphQL API.

Tokens
19K
Snippets
66
Records
84
Agent score
90%

What's inside Inertia.js

  1. What is Inertia.js?

    3.x

    Inertia.js is a communication layer that allows you to build modern single-page applications (SPAs) using React, Vue, or Svelte without the complexity of building a dedicated API.

    Instead of returning traditional HTML templates, your backend returns a page component along with its data. Inertia handles the connection between your backend and frontend, ensuring that page visits and interactions occur without full page reloads, while allowing you to keep your existing backend routing, controllers, models, and authorization logic.

  2. Core features of Inertia.js

    3.x

    Inertia provides several built-in capabilities for building production-ready applications:

    • Navigation & Forms: Page visits, form handling, file uploads with progress, and server-side validation.
    • Performance & UX: Optimistic updates (rendering before server response), partial reloads, deferred props, prefetching, polling, and infinite scroll.
    • Advanced Capabilities: Server-side rendering (SSR), code splitting, and view transitions.
    • Security: History encryption for pages containing sensitive data.
    • Developer Experience: DevTools to inspect requests, headers, and hydrated props.
  3. How Inertia.js works with Adapters

    3.x

    Inertia acts as the bridge between your backend and frontend through a system of adapters. It does not replace your existing frameworks; rather, it integrates with them.

    Frontend Adapters

    Official adapters for the following frameworks are maintained in the inertiajs/inertia repository:

    • React
    • Vue
    • Svelte

    Backend Adapters

    Inertia requires a server-side adapter to communicate with your backend.

    • Laravel: The officially maintained adapter.
    • Community Adapters: Available for Rails, Phoenix, Django, Symfony, AdonisJS, Go, .NET, and more.
  4. Configure SSR testing in Playwright

    3.x

    When SSR=true is set in the environment, the Playwright configuration switches from a standard single-server setup to a multi-server configuration to support different SSR modes. It also changes the test selection logic to include ssr.spec.ts files.

    • Standard Mode (SSR != true): Runs a single build and serve command. Tests ignore ssr.spec.ts.
    • SSR Mode (SSR=true): Runs multiple server configurations (SSR, SSR-Auto, and standard Serve) and includes ssr.spec.ts in the test match pattern.
  5. Define layouts for React components

    3.x

    In Inertia.js with React, you can define a layout property on your page components to wrap them in persistent layouts. This prevents the layout from re-rendering when navigating between pages that share the same layout.

    You can provide a layout in several ways:

    1. A single Layout Component: A component that accepts children as a prop.
    2. An array of Layout Components: For nested or multiple layouts.
    3. A Layout Function: A function that takes the page (as ReactNode) and returns the wrapped page.
    4. A Callback: A function that receives SharedPageProps and returns a layout component.
    // Example: Using a Layout Component
    export default {
      layout: MyPersistentLayout,
      render: () => <MyPage />
    }
    
    // Example: Using a Layout Function
    export default {
      layout: (page: ReactNode) => <MyPersistentLayout>{page}</MyPersistentLayout>,
      render: () => <MyPage />
    }
  6. Understand the Page object structure

    3.x

    The Page object represents the current state of the application. It contains the component being rendered, the props passed to it, and metadata about the current visit.

    Key properties:

    • component: The name of the component to render.
    • props: The data passed to the component, including errors and deferred props.
    • url: The current URL.
    • version: The current version of the page (used for stale data detection).
    • flash: The current flash data.
    • deferredProps: A record of props that are being loaded asynchronously.
  7. Extend Inertia configuration with TypeScript

    3.x

    You can override the core Inertia configuration types using TypeScript interface declaration merging. This allows you to define the exact shape of your sharedPageProps, layoutProps, flash data, and errorValueType to get full type safety across your application.

    To do this, create a declaration file (e.g., global.d.ts) and extend the InertiaConfig interface within the @inertiajs/core module.

    // global.d.ts
    import '@inertiajs/core'
    
    declare module '@inertiajs/core' {
      export interface InertiaConfig {
        errorValueType: string[]
        flashDataType: {
          toast?: { type: 'success' | 'error', message: string }
        }
        sharedPageProps: {
          auth: { user: User | null }
        }
        layoutProps: {
          title: string
          showSidebar: boolean
        }
        namedLayoutProps: {
          app: { title: string; theme: string }
          content: { padding: string; maxWidth: string }
        }
      }
    }
  8. Use Precognition for client-side validation

    3.x

    Inertia provides support for Laravel Precognition, allowing you to perform validation on the client side that mirrors your server-side validation logic. By calling withPrecognition(), the form object is extended with validation-specific methods.

    Validation Methods

    • validate(field?, config?): Triggers validation for a specific field or the whole form.
    • invalid(field): Returns true if the specified field has validation errors.
    • valid(field?): Returns true if the specified field (or the whole form) is valid.
    • touched(field?): Returns true if the field has been interacted with.
    • touch(field): Marks a field as 'touched'.
    • validateFiles(): Specifically triggers file validation.
    • validating: Boolean indicating if validation is currently in progress.
    const { data, setData, post, withPrecognition } = useForm({ email: '' })
    
    // Extend the form with precognition capabilities
    const form = withPrecognition()
    
    // Use validation methods
    if (form.invalid('email')) {
      console.log('Email is invalid')
    }
    
    // Trigger validation on change
    const handleChange = (e) => {
      setData('email', e.target.value)
      form.validate('email')
    }
  9. Define layouts for Inertia React components

    3.x

    Inertia React supports multiple ways to define layouts for your components. Layouts can be assigned directly to the component via a .layout property.

    Supported patterns:

    1. Static Layout: Assign a component directly to Component.layout.
    2. Layout Resolver: A function that returns a layout component or a configuration object.
    3. Layout with Props: A function that returns an object containing both a component and props to be passed to that layout.
    4. Default Layout: If no layout is defined on the component, the defaultLayout prop provided to the App component is used.

    When a layout is used, Inertia handles the nesting of components, allowing you to wrap your page content in persistent UI elements (like sidebars or navbars) that do not re-render during navigation.

  10. Configure the Inertia Svelte adapter

    3.x

    The config object allows you to extend the core Inertia configuration with Svelte-specific settings. This is useful for fine-tuning how the adapter behaves within your Svelte application.

    import { config } from '@inertiajs/svelte'
    
    config.extend({
      // Svelte-specific configuration options
    })
  11. Configure the Inertia React adapter

    3.x

    The config object allows you to extend the core Inertia configuration with React-specific settings. This is useful for fine-tuning how the adapter behaves within a React environment.

    import { config } from '@inertiajs/react'
    
    // config is an extended version of @inertiajs/core config