Inertia Rails Documentation

website·Indexed 30 days ago

https://inertia-rails.netlify.app

Documentation for the Inertia.js Rails adapter, enabling the creation of single-page apps using Ruby on Rails. Covers server-side configuration, client-side setup, form handling with useForm and <Form>, cached and deferred props, asset versioning, and integration with Vue, React, and Svelte.

Tokens
58.4K
Snippets
356
Records
413
Agent score
74%

What's inside Inertia Rails

  1. Overview of Inertia.js for Ruby on Rails

    Inertia.js is a tool that allows developers to build fully client-side rendered single-page apps (SPAs) using classic server-driven patterns. It acts as 'glue' between a server-side framework (like Ruby on Rails) and a client-side framework (such as React, Vue, or Svelte). Unlike traditional SPAs, Inertia does not require client-side routing or a dedicated API; instead, developers continue to build controllers and page views as they would in a standard monolith application.
  2. Overview of Inertia application testing strategies

    Testing an Inertia application typically involves three layers:

    1. End-to-end (E2E) Tests: Using tools like Cypress or Capybara to simulate real user interactions in a browser. This is the most confident way to test as it executes actual JavaScript.
    2. Client-Side Unit Tests: Using frameworks like Vitest, Jest, or Mocha to test JavaScript page components in isolation via Node.js.
    3. Endpoint Tests: Using server-side helpers (RSpec/Minitest) to verify that the correct Inertia components and props are being returned by the Rails controller.
  3. Understand the Inertia architecture and view layer

    Inertia allows developers to use standard server-side framework functionality (routing, controllers, middleware, authentication, and data fetching) while replacing the traditional server-side rendering templates (like Ruby or PHP templates) with JavaScript page components. This enables the use of frontend frameworks like React, Vue, or Svelte without abandoning the productivity of a server-side framework.
  4. Define routes for Inertia components in Rails

    In Inertia, all application routes are defined server-side, eliminating the need for client-side routers like Vue Router or React Router. You define standard Rails routes and return Inertia responses from the corresponding controller actions.
  5. Create and render Inertia pages in a Rails application

    Inertia pages are JavaScript components (Vue, React, or Svelte) that receive data from Rails controllers as props. This architecture eliminates the need for a separate API for page data and removes the need for 'loading' states since data is retrieved before the browser renders the page. To render a page, return an inertia response from a Rails controller.
    class UsersController < ApplicationController
      def show
        user = User.find(params[:id])
    
        # Renders the corresponding JS component (e.g., app/frontend/pages/users/show.vue)
        render inertia: { user: }
      end
    end
  6. Choose a caching strategy for Inertia Rails

    Inertia Rails provides four complementary caching strategies depending on what needs to be optimized:

    • HTTP Caching: Saves the entire response render. Best for pages tied to a single record's freshness. Lives in the Browser/CDN.
    • Cached Props: Saves block evaluation for expensive queries or computations. Lives in the server-side cache store.
    • Once Props: Saves bandwidth and serialization for large or rarely-changing shared data. Lives in client memory.
    • SSR Caching: Saves the SSR render request to avoid redundant Node.js calls. Lives in the server-side cache store.
  7. Listen for the prefetched event in Inertia

    The prefetched event fires when a page is prefetched. This event is not cancelable. You can listen for it using the router.on() method to access details about the prefetched visit, such as the URL.
    import { router } from '@inertiajs/react'
    
    router.on('prefetched', (event) => {
      console.log(`Prefetched ${event.detail.visit.url}`)
    })
  8. Understand the Inertia.js development paradigm

    Inertia.js allows developers to build single-page applications (SPAs) using modern JavaScript frameworks (React, Vue, or Svelte) without the need to create a separate REST or GraphQL API. It maintains the classic server-side rendered workflow—where controllers retrieve data via an ORM and render views—but replaces traditional server-side templates with JavaScript page components. This eliminates the need for client-side state management, API authentication/authorization layers, and complex deployment strategies typically associated with decoupled SPAs.
  9. Understand the Inertia request lifecycle

    The Inertia protocol handles the first visit differently from subsequent navigations to avoid full page reloads:

    1. First Visit: The browser makes a standard GET request. The server responds with a full HTML document containing a root <div> (mounting point) and a <script type="application/json"> element containing the initial Page Object. This boots the client-side framework.
    2. Subsequent Visits: Inertia makes XHR requests with the X-Inertia: true header. The server responds with a JSON payload (the Page Object) instead of HTML. Inertia then swaps the page component and updates the URL without reloading the page.
    sequenceDiagram
        participant Client
        participant Server
    
        Client->>Server: First Visit
        Server-->>Client: Returns HTML Skeleton
    
        Note over Client: Inertia.js is loaded
    
        Client->>Server: Inertia Request (X-Inertia: true)
        Server-->>Client: Returns JSON Payload (Component Name, Props, etc.)
    
        Note over Client: Inertia.js swaps components
  10. Prevent privileged data exposure using History Encryption

    Inertia.js provides history encryption to prevent users from viewing sensitive data stored in the browser's history state (e.g., after logging out). It uses the browser's crypto API to encrypt page data before pushing it to the history state, storing the key in session storage. This feature requires a secure environment (SSL enabled) as it relies on window.crypto.subtle.
  11. Understand default scroll behavior in Inertia

    By default, Inertia mimics standard browser behavior by resetting the scroll position of the document body (and any defined scroll regions) to the top when navigating between pages. Inertia also tracks the scroll position of each page to automatically restore it when the user navigates forward or backward through their browser history.