Skip to content

Inertia (React / Vue / Svelte)

Frontend

Inertia

Introduction

Building a single-page application usually means maintaining two separate applications: a JSON API on the server and a frontend client that manages routing and data fetching. Inertia lets you skip the API. You define routes and handlers as you would for server-rendered views, and each handler renders a React, Vue, or Svelte page component with the props it needs.

For example, a handler in src/http/handlers/posts.rs loads a post and passes it to the Posts/Show component:

1use laravel::inertia::{self, Page, props};
2 
3use crate::models::Post;
4 
5pub async fn show(post: Post) -> Page {
6 inertia::render("Posts/Show", props! { post })
7}
1use laravel::inertia::{self, Page, props};
2 
3use crate::models::Post;
4 
5pub async fn show(post: Post) -> Page {
6 inertia::render("Posts/Show", props! { post })
7}

Your React component in resources/js/pages/Posts/Show.tsx receives post directly as a prop:

1type Post = {
2 id: number;
3 title: string;
4 body: string;
5};
6 
7export default function Show({ post }: { post: Post }) {
8 return (
9 <article>
10 <h1>{post.title}</h1>
11 <p>{post.body}</p>
12 </article>
13 );
14}
1type Post = {
2 id: number;
3 title: string;
4 body: string;
5};
6 
7export default function Show({ post }: { post: Post }) {
8 return (
9 <article>
10 <h1>{post.title}</h1>
11 <p>{post.body}</p>
12 </article>
13 );
14}

Inertia support is built into Laravel via the inertia Cargo feature, which is enabled by default. New Laravel applications come pre-configured with React, TypeScript, Tailwind, and Vite Plus, and register the Inertia middleware for you, so you can start rendering pages right away.

This guide covers how Inertia integrates with Laravel and its most common features. For complete details on client-side features such as persistent layouts, manual visits, scroll management, and Vue or Svelte adapters, check out the Inertia documentation.

The Inertia middleware

You configure Inertia in your application's HandleInertiaRequests middleware inside src/http/middleware. It implements the inertia::Middleware trait, whose methods all have defaults so you only override what you need. By default, new applications share the application's name with every page and render errors using the Error page component:

1use laravel::inertia::{self, Props, props};
2use laravel::prelude::*;
3 
4pub struct HandleInertiaRequests;
5 
6impl inertia::Middleware for HandleInertiaRequests {
7 async fn share(&self, _request: &Request) -> laravel::Result<Props> {
8 Ok(props! {
9 name => laravel::config().app.name.clone(),
10 })
11 }
12 
13 fn error_page(&self) -> Option<&str> {
14 Some("Error")
15 }
16}
1use laravel::inertia::{self, Props, props};
2use laravel::prelude::*;
3 
4pub struct HandleInertiaRequests;
5 
6impl inertia::Middleware for HandleInertiaRequests {
7 async fn share(&self, _request: &Request) -> laravel::Result<Props> {
8 Ok(props! {
9 name => laravel::config().app.name.clone(),
10 })
11 }
12 
13 fn error_page(&self) -> Option<&str> {
14 Some("Error")
15 }
16}

The trait's other methods customize the root view and asset version, and configure adjusts settings such as history encryption.

New applications register HandleInertiaRequests on the web middleware group in src/app.rs:

1.with_middleware(|middleware, _| {
2 middleware.web(|web| {
3 web.append(inertia::middleware(HandleInertiaRequests));
4 });
5})
1.with_middleware(|middleware, _| {
2 middleware.web(|web| {
3 web.append(inertia::middleware(HandleInertiaRequests));
4 });
5})

Inertia works only on routes that run HandleInertiaRequests. Calling inertia::render on a route outside the web group, such as an api route, returns a server error.

The root view

A user's first visit to your application receives a full HTML document called the root view, which bootstraps your frontend and mounts the page. Subsequent visits fetch only the next page's JSON data. By default, the root view is resources/views/app.html:

1<!DOCTYPE html>
2<html lang="en">
3 <head>
4 <meta charset="utf-8">
5 {{ vite_react_refresh() }}
6 {{ vite("resources/js/app.tsx", "resources/js/pages/" ~ page.component ~ ".tsx") }}
7 {{ inertia_head }}
8 </head>
9 <body>
10 {{ inertia }}
11 </body>
12</html>
1<!DOCTYPE html>
2<html lang="en">
3 <head>
4 <meta charset="utf-8">
5 {{ vite_react_refresh() }}
6 {{ vite("resources/js/app.tsx", "resources/js/pages/" ~ page.component ~ ".tsx") }}
7 {{ inertia_head }}
8 </head>
9 <body>
10 {{ inertia }}
11 </body>
12</html>
In the root view What it renders
{{ inertia }} The root element where Inertia mounts the page.
{{ inertia_head }} The page's head metadata.
{{ page }} The page object containing component, props, url, and version.
{{ vite(...) }} The asset tags for your Vite entry points.
{{ vite_react_refresh() }} React Fast Refresh while Vite's development server is running.

The root view is a standard view. It has access to data shared with every view and may extend a layout. To pass data only to the root view for a single response without sending it as an Inertia prop, chain with_view_data onto render:

1inertia::render("Dashboard", ()).with_view_data("theme", "dark")
1inertia::render("Dashboard", ()).with_view_data("theme", "dark")

Outside debug mode, Laravel caches the root view and Vite's manifest on startup, so restart your application after rebuilding your frontend assets.

Using another root view

To render a different template as your root view, override root_view on HandleInertiaRequests and pass the view's name to page.view:

1use laravel::inertia::{self, RootPage};
2use laravel::view::Html;
3 
4impl inertia::Middleware for HandleInertiaRequests {
5 fn root_view(&self, page: &RootPage<'_>) -> laravel::Result<Html> {
6 page.view("layouts.inertia").render()
7 }
8}
1use laravel::inertia::{self, RootPage};
2use laravel::view::Html;
3 
4impl inertia::Middleware for HandleInertiaRequests {
5 fn root_view(&self, page: &RootPage<'_>) -> laravel::Result<Html> {
6 page.view("layouts.inertia").render()
7 }
8}

Rendering pages

To render an Inertia page from a handler, call inertia::render with the page component's name and its props:

1use laravel::inertia::{self, Page, props};
2 
3use crate::models::User;
4 
5pub async fn show(user: User) -> Page {
6 inertia::render("Users/Show", props! { user })
7}
1use laravel::inertia::{self, Page, props};
2 
3use crate::models::User;
4 
5pub async fn show(user: User) -> Page {
6 inertia::render("Users/Show", props! { user })
7}

Page components live in resources/js/pages, so "Users/Show" renders resources/js/pages/Users/Show.tsx.

If a page needs no props beyond your shared data, pass () as the second argument to inertia::render("Dashboard", ()). If the page doesn't need a handler at all, register it directly with route.inertia("/about", "About").

Props

Build props with the props! macro, which works like data! for views. It accepts local variables by name as well as name => value pairs. Quote keys that aren't valid Rust identifiers, such as dot-notation paths for nested props:

1inertia::render(
2 "Users/Show",
3 props! { user, can_edit => true, "auth.permissions" => ["edit"] },
4)
1inertia::render(
2 "Users/Show",
3 props! { user, can_edit => true, "auth.permissions" => ["edit"] },
4)

Keys keep the exact casing you write, so can_edit stays can_edit. If your frontend expects camelCase, write canEdit => can_edit. A variable listed by itself is borrowed so you can keep using it afterward, while a name => value pair takes ownership unless you pass &value.

You may include props conditionally using if, else if, else, and if let blocks inside props!:

1inertia::render("Users/Show", props! {
2 user,
3 if user.is_admin {
4 can_edit => true,
5 }
6 if let Some(team) = &user.team {
7 team,
8 }
9})
1inertia::render("Users/Show", props! {
2 user,
3 if user.is_admin {
4 can_edit => true,
5 }
6 if let Some(team) = &user.team {
7 team,
8 }
9})

A prop inside a false if block is omitted completely rather than sent as null (unlike an Option::None value). If a conditional expression returns a prop helper such as inertia::once on one branch and null on the other, use inertia::null() so both branches have the same Prop type:

1inertia::render("Users/Show", props! {
2 user => if let Some(user) = user {
3 inertia::once(async move || user)
4 } else {
5 inertia::null()
6 },
7})
1inertia::render("Users/Show", props! {
2 user => if let Some(user) = user {
3 inertia::once(async move || user)
4 } else {
5 inertia::null()
6 },
7})

If you prefer typed structs, you may pass any Serialize struct to inertia::render instead of props!:

1#[derive(Serialize)]
2struct ShowProps {
3 user: User,
4 can_edit: bool,
5}
6 
7inertia::render("Users/Show", ShowProps { user, can_edit: true })
1#[derive(Serialize)]
2struct ShowProps {
3 user: User,
4 can_edit: bool,
5}
6 
7inertia::render("Users/Show", ShowProps { user, can_edit: true })

Every prop is sent to the browser and visible to anyone inspecting the page. Send only what the page needs and mark private model fields with #[serde(skip)]. PasswordHash and RememberToken don't implement Serialize, so they can never be exposed in props by accident.

Deferred props

When a page includes expensive data that shouldn't delay the initial page render, such as a user's posts or dashboard analytics, wrap it in inertia::defer. Inertia omits the prop from the first response and fetches it automatically in a background request right after the page mounts:

1use laravel::inertia::{self, Page, props};
2 
3use crate::models::{Post, User};
4 
5pub async fn show(user: User) -> Page {
6 let user_id = user.id;
7 
8 inertia::render("Users/Show", props! {
9 user,
10 posts => inertia::defer(async move || {
11 Post::query().filter(Post::user_id.eq(user_id)).get().await
12 }),
13 })
14}
1use laravel::inertia::{self, Page, props};
2 
3use crate::models::{Post, User};
4 
5pub async fn show(user: User) -> Page {
6 let user_id = user.id;
7 
8 inertia::render("Users/Show", props! {
9 user,
10 posts => inertia::defer(async move || {
11 Post::query().filter(Post::user_id.eq(user_id)).get().await
12 }),
13 })
14}

Because prop callbacks run after your handler returns, they can't borrow local variables from the handler. Capture owned values with async move, copying or cloning anything the handler also needs (such as user_id above).

On the frontend, wrap the deferred content in Inertia's <Deferred> component and pass a fallback element to display while the prop is loading:

1import { Deferred } from "@inertiajs/react";
2 
3type User = { id: number; name: string };
4type Post = { id: number; title: string };
5 
6export default function Show({ user, posts }: { user: User; posts?: Post[] }) {
7 return (
8 <div>
9 <h1>{user.name}</h1>
10 
11 <Deferred data="posts" fallback={<div>Loading posts...</div>}>
12 <ul>
13 {posts?.map((post) => (
14 <li key={post.id}>{post.title}</li>
15 ))}
16 </ul>
17 </Deferred>
18 </div>
19 );
20}
1import { Deferred } from "@inertiajs/react";
2 
3type User = { id: number; name: string };
4type Post = { id: number; title: string };
5 
6export default function Show({ user, posts }: { user: User; posts?: Post[] }) {
7 return (
8 <div>
9 <h1>{user.name}</h1>
10 
11 <Deferred data="posts" fallback={<div>Loading posts...</div>}>
12 <ul>
13 {posts?.map((post) => (
14 <li key={post.id}>{post.title}</li>
15 ))}
16 </ul>
17 </Deferred>
18 </div>
19 );
20}

By default, all deferred props on a page are fetched together in a single follow-up request. To fetch slower props in a separate parallel request, assign them to a named group with .group(...). You may also chain .rescue() so a failing prop doesn't prevent the other props in the request from loading:

1posts => inertia::defer(async move || {
2 Post::query().filter(Post::user_id.eq(user_id)).get().await
3})
4.group("posts")
5.rescue(),
1posts => inertia::defer(async move || {
2 Post::query().filter(Post::user_id.eq(user_id)).get().await
3})
4.group("posts")
5.rescue(),

Load when visible

Sometimes a section further down the page, such as comments or related items, doesn't need to be loaded unless the user actually scrolls to it. Pair inertia::optional on the server with Inertia's <WhenVisible> component on the frontend:

1use laravel::inertia::{self, Page, props};
2 
3use crate::models::{Comment, Post};
4 
5pub async fn show(post: Post) -> Page {
6 let post_id = post.id;
7 
8 inertia::render("Posts/Show", props! {
9 post,
10 comments => inertia::optional(async move || {
11 Comment::query().filter(Comment::post_id.eq(post_id)).get().await
12 }),
13 })
14}
1use laravel::inertia::{self, Page, props};
2 
3use crate::models::{Comment, Post};
4 
5pub async fn show(post: Post) -> Page {
6 let post_id = post.id;
7 
8 inertia::render("Posts/Show", props! {
9 post,
10 comments => inertia::optional(async move || {
11 Comment::query().filter(Comment::post_id.eq(post_id)).get().await
12 }),
13 })
14}

On the frontend, <WhenVisible> watches the element with an IntersectionObserver and automatically requests the comments prop once it enters the viewport:

1import { WhenVisible } from "@inertiajs/react";
2 
3export default function Show({ post, comments }: { post: Post; comments?: Comment[] }) {
4 return (
5 <article>
6 <h1>{post.title}</h1>
7 <p>{post.body}</p>
8 
9 <WhenVisible data="comments" fallback={<div>Loading comments...</div>}>
10 <ul>
11 {comments?.map((comment) => (
12 <li key={comment.id}>{comment.body}</li>
13 ))}
14 </ul>
15 </WhenVisible>
16 </article>
17 );
18}
1import { WhenVisible } from "@inertiajs/react";
2 
3export default function Show({ post, comments }: { post: Post; comments?: Comment[] }) {
4 return (
5 <article>
6 <h1>{post.title}</h1>
7 <p>{post.body}</p>
8 
9 <WhenVisible data="comments" fallback={<div>Loading comments...</div>}>
10 <ul>
11 {comments?.map((comment) => (
12 <li key={comment.id}>{comment.body}</li>
13 ))}
14 </ul>
15 </WhenVisible>
16 </article>
17 );
18}

You may pass a pixel buffer prop, such as buffer={500}, to start loading the data before the user scrolls all the way to the element.

Lazy and other props

Beyond deferred props, Inertia provides prop helpers that control when each prop is evaluated and how the client updates it during partial reloads (such as router.reload({ only: ['posts'] }) when a user changes a filter):

Prop Behavior
inertia::lazy(async || { .. }) Evaluated only when the prop is included in the response.
inertia::optional(..) Sent only when a partial reload explicitly requests it.
inertia::always(value) Included in every response, even partial reloads that didn't ask for it.
inertia::merge(value) Appended to the existing prop value on the client, such as in "load more" lists.
inertia::once(..) Resolved once and cached on the client. Chain .until(7.days()) to expire it after a span of time, or .fresh_if(cond) to force a refresh conditionally.
inertia::scroll_with(async || { .. }) Wraps a paginator for Inertia's <InfiniteScroll> component (inertia::scroll(paginator) wraps one you already fetched).

You may chain .when(condition, |prop| ..) on any prop to apply modifiers conditionally. Any prop callback may return laravel::Result and use ?. Laravel handles callback errors as it does handler errors, so or_abort works inside callbacks as well.

Shared data

Some data belongs on every page, such as the logged-in user shown in your navigation bar. Rather than passing it from every handler, return it from HandleInertiaRequests::share so every page receives it alongside its own props. Because share is async and returns laravel::Result, it may query the database and use ?. Keep shared data lean, since every Inertia response carries it.

To share the logged-in user, call request.user(). Pages receive null for guests:

1use laravel::inertia::{self, Props, props};
2use laravel::prelude::*;
3use serde_json::json;
4 
5use crate::models::User;
6 
7impl inertia::Middleware for HandleInertiaRequests {
8 async fn share(&self, request: &Request) -> laravel::Result<Props> {
9 let user: Option<User> = request.user().await?;
10 
11 Ok(props! {
12 auth => json!({ "user": user }),
13 })
14 }
15}
1use laravel::inertia::{self, Props, props};
2use laravel::prelude::*;
3use serde_json::json;
4 
5use crate::models::User;
6 
7impl inertia::Middleware for HandleInertiaRequests {
8 async fn share(&self, request: &Request) -> laravel::Result<Props> {
9 let user: Option<User> = request.user().await?;
10 
11 Ok(props! {
12 auth => json!({ "user": user }),
13 })
14 }
15}

share runs on every request before your handler. If a shared prop is expensive to compute or may be modified by your handler (such as a shopping cart count stored in the session), wrap it in inertia::lazy so Inertia evaluates it when the page renders after your handler returns. Because a lazy callback can't borrow request, clone the Session handle (which shares the request's session data) and move it into the closure:

1async fn share(&self, request: &Request) -> laravel::Result<Props> {
2 let session = request.session()?.clone();
3 
4 Ok(props! {
5 cartCount => inertia::lazy(async move || {
6 session.get::<Vec<String>>("cart").unwrap_or_default().len()
7 }),
8 })
9}
1async fn share(&self, request: &Request) -> laravel::Result<Props> {
2 let session = request.session()?.clone();
3 
4 Ok(props! {
5 cartCount => inertia::lazy(async move || {
6 session.get::<Vec<String>>("cart").unwrap_or_default().len()
7 }),
8 })
9}

Because share reads the authenticated user before your handler runs, always redirect after logging a user in or out so the next page receives the updated user.

To navigate between pages without triggering a full browser reload, use Inertia's <Link> component in place of standard <a> tags:

1import { Link } from "@inertiajs/react";
2 
3export default function Navigation() {
4 return (
5 <nav>
6 <Link href="/dashboard">Dashboard</Link>
7 <Link href="/posts">Posts</Link>
8 <Link href="/logout" method="post" as="button">
9 Log out
10 </Link>
11 </nav>
12 );
13}
1import { Link } from "@inertiajs/react";
2 
3export default function Navigation() {
4 return (
5 <nav>
6 <Link href="/dashboard">Dashboard</Link>
7 <Link href="/posts">Posts</Link>
8 <Link href="/logout" method="post" as="button">
9 Log out
10 </Link>
11 </nav>
12 );
13}

When a link uses a method other than GET (such as POST or DELETE), pass as="button" so Inertia renders a <button> element instead of an anchor tag.

Prefetching

To make navigation feel instantaneous, add the prefetch prop to any <Link>. By default, Inertia prefetches the destination page's data when the user hovers over the link for more than 75 milliseconds and caches the response briefly so clicking the link renders immediately:

1import { Link } from "@inertiajs/react";
2 
3<Link href="/dashboard" prefetch>
4 Dashboard
5</Link>
1import { Link } from "@inertiajs/react";
2 
3<Link href="/dashboard" prefetch>
4 Dashboard
5</Link>

To prefetch a page as soon as the link mounts rather than waiting for hover, pass prefetch="mount". You may also customize how long the prefetched response is cached with cacheFor:

1<Link href="/dashboard" prefetch="mount" cacheFor="1m">
2 Dashboard
3</Link>
1<Link href="/dashboard" prefetch="mount" cacheFor="1m">
2 Dashboard
3</Link>

Because a user might hover over a link without clicking it, you can check request.prefetch() in your Rust handler to skip side effects such as incrementing a page view counter.

Forms

Inertia's <Form> component and useForm hook submit standard HTTP requests to your Laravel handlers without triggering a full browser reload. Your handler validates the input, saves the data, and returns a redirect, and Inertia updates the page (or displays validation errors) automatically.

For most forms, Inertia's <Form> component works like a standard HTML <form> while exposing errors, processing, and other state through a render prop:

1import { Form } from "@inertiajs/react";
2 
3export default function CreatePost() {
4 return (
5 <Form action="/posts" method="post">
6 {({ errors, processing }) => (
7 <>
8 <div>
9 <input type="text" name="title" placeholder="Title" />
10 {errors.title && <p>{errors.title}</p>}
11 </div>
12 
13 <div>
14 <textarea name="body" placeholder="Write your post..." />
15 {errors.body && <p>{errors.body}</p>}
16 </div>
17 
18 <button type="submit" disabled={processing}>
19 {processing ? "Publishing..." : "Publish"}
20 </button>
21 </>
22 )}
23 </Form>
24 );
25}
1import { Form } from "@inertiajs/react";
2 
3export default function CreatePost() {
4 return (
5 <Form action="/posts" method="post">
6 {({ errors, processing }) => (
7 <>
8 <div>
9 <input type="text" name="title" placeholder="Title" />
10 {errors.title && <p>{errors.title}</p>}
11 </div>
12 
13 <div>
14 <textarea name="body" placeholder="Write your post..." />
15 {errors.body && <p>{errors.body}</p>}
16 </div>
17 
18 <button type="submit" disabled={processing}>
19 {processing ? "Publishing..." : "Publish"}
20 </button>
21 </>
22 )}
23 </Form>
24 );
25}

When you need programmatic control over form state, such as modifying fields dynamically or resetting values after submission, use the useForm hook instead:

1import { useForm } from "@inertiajs/react";
2 
3export default function CreatePost() {
4 const { data, setData, post, processing, errors } = useForm({
5 title: "",
6 body: "",
7 });
8 
9 function submit(event: React.FormEvent) {
10 event.preventDefault();
11 post("/posts");
12 }
13 
14 return (
15 <form onSubmit={submit}>
16 <div>
17 <input
18 type="text"
19 value={data.title}
20 onChange={(event) => setData("title", event.target.value)}
21 />
22 {errors.title && <p>{errors.title}</p>}
23 </div>
24 
25 <div>
26 <textarea
27 value={data.body}
28 onChange={(event) => setData("body", event.target.value)}
29 />
30 {errors.body && <p>{errors.body}</p>}
31 </div>
32 
33 <button type="submit" disabled={processing}>
34 Publish
35 </button>
36 </form>
37 );
38}
1import { useForm } from "@inertiajs/react";
2 
3export default function CreatePost() {
4 const { data, setData, post, processing, errors } = useForm({
5 title: "",
6 body: "",
7 });
8 
9 function submit(event: React.FormEvent) {
10 event.preventDefault();
11 post("/posts");
12 }
13 
14 return (
15 <form onSubmit={submit}>
16 <div>
17 <input
18 type="text"
19 value={data.title}
20 onChange={(event) => setData("title", event.target.value)}
21 />
22 {errors.title && <p>{errors.title}</p>}
23 </div>
24 
25 <div>
26 <textarea
27 value={data.body}
28 onChange={(event) => setData("body", event.target.value)}
29 />
30 {errors.body && <p>{errors.body}</p>}
31 </div>
32 
33 <button type="submit" disabled={processing}>
34 Publish
35 </button>
36 </form>
37 );
38}

On the server, your handler validates the submission with Valid<T>, saves the record, and returns a redirect:

1use laravel::model::create;
2use laravel::prelude::*;
3 
4use crate::models::{Post, User};
5 
6#[laravel::input(fills = Post)]
7#[validate(authenticated)]
8pub struct NewPost {
9 #[validate(required, max_length(255))]
10 pub title: String,
11 #[validate(required)]
12 pub body: String,
13}
14 
15pub async fn store(
16 Authenticated(user): Authenticated<User>,
17 Valid(input): Valid<NewPost>,
18) -> laravel::Result<Redirect> {
19 let post = create!(Post { user: &user, ..input }).await?;
20 
21 Ok(redirect!(posts::show, &post))
22}
1use laravel::model::create;
2use laravel::prelude::*;
3 
4use crate::models::{Post, User};
5 
6#[laravel::input(fills = Post)]
7#[validate(authenticated)]
8pub struct NewPost {
9 #[validate(required, max_length(255))]
10 pub title: String,
11 #[validate(required)]
12 pub body: String,
13}
14 
15pub async fn store(
16 Authenticated(user): Authenticated<User>,
17 Valid(input): Valid<NewPost>,
18) -> laravel::Result<Redirect> {
19 let post = create!(Post { user: &user, ..input }).await?;
20 
21 Ok(redirect!(posts::show, &post))
22}

If validation fails, Laravel redirects back automatically and populates errors on the page so <Form> and useForm display each field's error right away while keeping the user's input intact.

To learn more about file uploads, resetting fields, dirty state, and other client-side form options, check out the Inertia forms documentation.

Validation errors

Validate form submissions using typed validation with Valid<T> or request.validate::<T>().await?. When validation fails, Laravel redirects back automatically and populates the page's errors prop so Inertia's form helpers display each field's error.

If your handler detects an error that validation rules didn't catch, such as a name that is already taken, return it with invalid!, which redirects back and populates the errors prop automatically:

1use laravel::validation::invalid;
2 
3invalid!(name => "This name is already in use.");
1use laravel::validation::invalid;
2 
3invalid!(name => "This name is already in use.");

Flash data

After saving a form, you'll often want to show a toast or confirmation banner on the next page. Call inertia::flash, which works like session flash data but delivers the value in the page's flash field rather than its props, so the message doesn't reappear when the user navigates with their browser's back button:

1use laravel::inertia;
2use laravel::prelude::*;
3 
4pub async fn store() -> laravel::Result<Redirect> {
5 // Create the user...
6 
7 inertia::flash("toast", "User created!")?;
8 
9 Ok(Redirect::back())
10}
1use laravel::inertia;
2use laravel::prelude::*;
3 
4pub async fn store() -> laravel::Result<Redirect> {
5 // Create the user...
6 
7 inertia::flash("toast", "User created!")?;
8 
9 Ok(Redirect::back())
10}

The flashed value may be any type that serializes to JSON. To flash data onto a page you are rendering directly, chain flash onto inertia::render:

1inertia::render("Users/Index", props! { users }).flash("toast", "Welcome back!")
1inertia::render("Users/Index", props! { users }).flash("toast", "Welcome back!")

If you'd like to flash a message and redirect in a single chain, take Inertia as a handler argument:

1use laravel::inertia::{HttpResponse, Inertia};
2 
3pub async fn update(inertia: Inertia) -> HttpResponse {
4 // Update the user...
5 
6 inertia.flash("toast", "User updated!").back()
7}
1use laravel::inertia::{HttpResponse, Inertia};
2 
3pub async fn update(inertia: Inertia) -> HttpResponse {
4 // Update the user...
5 
6 inertia.flash("toast", "User updated!").back()
7}

In your React layout, read flashed values from usePage().flash. Inertia types flash values as unknown by default, so check that toast is a string before rendering it:

1import { usePage } from '@inertiajs/react';
2import type { ReactNode } from 'react';
3 
4export default function Layout({ children }: { children: ReactNode }) {
5 const { toast } = usePage().flash;
6 
7 return (
8 <main>
9 {typeof toast === 'string' && <div role="status">{toast}</div>}
10 {children}
11 </main>
12 );
13}
1import { usePage } from '@inertiajs/react';
2import type { ReactNode } from 'react';
3 
4export default function Layout({ children }: { children: ReactNode }) {
5 const { toast } = usePage().flash;
6 
7 return (
8 <main>
9 {typeof toast === 'string' && <div role="status">{toast}</div>}
10 {children}
11 </main>
12 );
13}

Redirects

Redirect from Inertia handlers using Redirect as usual. After a PUT, PATCH, or DELETE request, Laravel automatically converts 302 redirects into 303 so the browser follows the redirect with a GET request.

Because an Inertia XHR visit can't follow a redirect to another domain, return inertia::location when redirecting to an external URL (such as a Stripe checkout page) or when you want to force a full page reload:

1use laravel::inertia::{self, HttpResponse};
2 
3pub async fn billing() -> laravel::Result<HttpResponse> {
4 inertia::location("https://billing.stripe.com/p/session/test_123")
5}
1use laravel::inertia::{self, HttpResponse};
2 
3pub async fn billing() -> laravel::Result<HttpResponse> {
4 inertia::location("https://billing.stripe.com/p/session/test_123")
5}

Polling

When a page needs to stay up to date on a regular interval without setting up WebSockets, use Inertia's usePoll hook. Pass the polling interval in milliseconds, and Inertia automatically reloads the page on that schedule and stops polling when the component unmounts:

1import { usePoll } from "@inertiajs/react";
2 
3export default function Dashboard({ stats }: { stats: Stats }) {
4 usePoll(5000);
5 
6 return <div>Active users: {stats.activeUsers}</div>;
7}
1import { usePoll } from "@inertiajs/react";
2 
3export default function Dashboard({ stats }: { stats: Stats }) {
4 usePoll(5000);
5 
6 return <div>Active users: {stats.activeUsers}</div>;
7}

To refresh only specific props on each poll, pass partial reload options as the second argument. You may also destructure start and stop to control polling manually:

1import { usePoll } from "@inertiajs/react";
2 
3export default function Notifications({ notifications }: { notifications: Notification[] }) {
4 const { start, stop } = usePoll(
5 5000,
6 { only: ["notifications"] },
7 { autoStart: false },
8 );
9 
10 return (
11 <div>
12 <button onClick={start}>Start polling</button>
13 <button onClick={stop}>Stop polling</button>
14 </div>
15 );
16}
1import { usePoll } from "@inertiajs/react";
2 
3export default function Notifications({ notifications }: { notifications: Notification[] }) {
4 const { start, stop } = usePoll(
5 5000,
6 { only: ["notifications"] },
7 { autoStart: false },
8 );
9 
10 return (
11 <div>
12 <button onClick={start}>Start polling</button>
13 <button onClick={stop}>Stop polling</button>
14 </div>
15 );
16}

Live props

Some pages display values that change while the user is viewing them, such as an order's status or an unread notification count. A live prop automatically refreshes whenever the page receives a matching broadcast event. By default, Inertia's client triggers a partial reload for that prop so it receives the latest value from your handler.

To make a prop live, pass inertia::on(&event) to its live method. The prop listens on every channel that the event broadcasts on:

1use laravel::event::Event;
2use laravel::inertia::{self, Page, props};
3use laravel::prelude::*;
4 
5use crate::models::Order;
6 
7#[derive(Event)]
8#[event(broadcast(private = "orders.{order_id}"))]
9pub struct OrderUpdated {
10 pub order_id: i64,
11}
12 
13pub async fn show(Params(order_id): Params<i64>) -> laravel::Result<Page> {
14 Ok(inertia::render("Orders/Show", props! {
15 order => inertia::lazy(async move || Order::find(order_id).await)
16 .live(inertia::on(&OrderUpdated { order_id })?),
17 }))
18}
1use laravel::event::Event;
2use laravel::inertia::{self, Page, props};
3use laravel::prelude::*;
4 
5use crate::models::Order;
6 
7#[derive(Event)]
8#[event(broadcast(private = "orders.{order_id}"))]
9pub struct OrderUpdated {
10 pub order_id: i64,
11}
12 
13pub async fn show(Params(order_id): Params<i64>) -> laravel::Result<Page> {
14 Ok(inertia::render("Orders/Show", props! {
15 order => inertia::lazy(async move || Order::find(order_id).await)
16 .live(inertia::on(&OrderUpdated { order_id })?),
17 }))
18}

inertia::on only inspects the event's channel names and event name; it doesn't dispatch the event. To refresh a prop in response to multiple events, call .live(...) once for each event. Live props may also be defer, optional, once, or always, though merge props can't be live.

Set up the client

Live props require Inertia's frontend client 3.11 or later and a transport passed to the live option of createInertiaApp. When using Reverb with React, install and configure Echo, then pass the echo() transport in resources/js/app.tsx:

1import { createInertiaApp } from '@inertiajs/react';
2import { echo } from '@inertiajs/react/echo';
3import { configureEcho } from '@laravel/echo-react';
4 
5configureEcho({
6 broadcaster: 'reverb',
7 namespace: false,
8});
9 
10createInertiaApp({
11 live: echo(),
12 // ...
13});
1import { createInertiaApp } from '@inertiajs/react';
2import { echo } from '@inertiajs/react/echo';
3import { configureEcho } from '@laravel/echo-react';
4 
5configureEcho({
6 broadcaster: 'reverb',
7 namespace: false,
8});
9 
10createInertiaApp({
11 live: echo(),
12 // ...
13});

Inertia subscribes and unsubscribes automatically as users navigate between pages. Private and presence channels require channel authorization; to learn more, check out the broadcasting guide's section on authorizing subscriptions.

To test live props locally, configure broadcasting to use Reverb and run laravel reverb:start alongside your application and queue worker. To learn more about running the local server, check out the WebSockets guide.

Listen on one channel

By default, a live prop listens on every channel its event broadcasts on. If OrderUpdated broadcasts on both orders.42 and orders, the prop would refresh whenever any order changes. To listen on a single specific channel, or to subscribe without constructing an event value, use inertia::on_channel:

1use laravel::broadcast::Channel;
2 
3orders => inertia::defer(async || Order::all().await)
4 .live(inertia::on_channel::<OrderUpdated>(Channel::private("orders")?)),
1use laravel::broadcast::Channel;
2 
3orders => inertia::defer(async || Order::all().await)
4 .live(inertia::on_channel::<OrderUpdated>(Channel::private("orders")?)),

on_channel uses the event name generated by #[derive(Event)]. If your event overrides broadcast_as manually, use inertia::on with an event instance instead.

Throttle refreshes

By default, Inertia's client refreshes each live prop at most once per second. To change that interval for a specific prop, chain .throttle(...) with a duration. Events received during the interval are coalesced into a single refresh:

1orders => inertia::defer(async || Order::all().await)
2 .live(inertia::on_channel::<OrderUpdated>(Channel::private("orders")?))
3 .throttle(5.seconds()),
1orders => inertia::defer(async || Order::all().await)
2 .live(inertia::on_channel::<OrderUpdated>(Channel::private("orders")?))
3 .throttle(5.seconds()),

Broadcast new values

By default, every open tab listening for an event sends a partial reload request back to your server, which can create a spike of traffic if a dashboard is open in thousands of browsers at once. To push updated prop values directly inside the broadcast payload instead, implement broadcast_props in a custom Broadcast implementation, keyed by prop name:

1use laravel::broadcast::{Broadcast, Channel};
2use laravel::event::Event;
3use serde_json::{Value, json};
4 
5#[derive(Event)]
6#[event(broadcast)]
7pub struct OrderUpdated {
8 pub order_id: u64,
9 pub status: String,
10}
11 
12impl Broadcast for OrderUpdated {
13 fn broadcast_on(&self) -> laravel::Result<Vec<Channel>> {
14 Ok(vec![Channel::private(format!("orders.{}", self.order_id))?])
15 }
16 
17 fn broadcast_props(&self) -> laravel::Result<Value> {
18 Ok(json!({ "order": { "id": self.order_id, "status": self.status } }))
19 }
20}
1use laravel::broadcast::{Broadcast, Channel};
2use laravel::event::Event;
3use serde_json::{Value, json};
4 
5#[derive(Event)]
6#[event(broadcast)]
7pub struct OrderUpdated {
8 pub order_id: u64,
9 pub status: String,
10}
11 
12impl Broadcast for OrderUpdated {
13 fn broadcast_on(&self) -> laravel::Result<Vec<Channel>> {
14 Ok(vec![Channel::private(format!("orders.{}", self.order_id))?])
15 }
16 
17 fn broadcast_props(&self) -> laravel::Result<Value> {
18 Ok(json!({ "order": { "id": self.order_id, "status": self.status } }))
19 }
20}

Inertia's client updates those props directly in the browser without making an extra HTTP request.

Inertia's client sends the page's socket ID on every request, so dispatching the event with broadcast::event(event).to_others() skips refreshing the tab that triggered the change. To learn more about broadcast dispatch options, check out the broadcasting guide's section on dispatch options.

Every subscriber on a channel receives the exact same broadcast payload. Only broadcast prop values that every subscriber is allowed to see, and let per-user data refresh via a normal partial reload.

Error pages

When an error occurs or a visitor requests a missing URL, you usually want the error page to match your application's layout. Return a component name from HandleInertiaRequests::error_page to render errors with that Inertia component:

1use laravel::inertia;
2 
3impl inertia::Middleware for HandleInertiaRequests {
4 fn error_page(&self) -> Option<&str> {
5 Some("Error")
6 }
7}
1use laravel::inertia;
2 
3impl inertia::Middleware for HandleInertiaRequests {
4 fn error_page(&self) -> Option<&str> {
5 Some("Error")
6 }
7}

Your Error component receives an error prop holding the error's status and message (matching the message shown on built-in error pages) along with your shared props. Treat shared props as optional inside Error, because any shared prop that fails to resolve is omitted from the error page. API requests that want JSON still receive JSON, and server failures in debug mode still display the debug page.

On routes that run HandleInertiaRequests, this component replaces HTML error views. Because an unmatched URL doesn't run route middleware, new applications end src/routes/web.rs with route.fallback(async || laravel::abort(404)) so 404 pages render through your Inertia Error component as well.

Rendering an error as a page

To render a specific error type with a dedicated Inertia page, such as a declined-card page with a link to update billing details, register an error renderer in src/app.rs and render the page through request.inertia():

1use laravel::inertia::props;
2use laravel::prelude::*;
3use serde_json::json;
4 
5#[derive(Debug, thiserror::Error)]
6#[error("Your card was declined.")]
7pub struct CardDeclined {
8 pub code: String,
9}
10 
11Application::configure()
12 .with_errors(|errors, _| {
13 errors
14 .status::<CardDeclined>(402)
15 .render(|error: &CardDeclined, request, status| {
16 if request.wants_json() {
17 let body = json!({
18 "message": error.to_string(),
19 "code": error.code,
20 });
21 
22 return Some((status, Json(body)).into_response());
23 }
24 
25 let page = request
26 .inertia()?
27 .render("Billing/CardDeclined", props! { code => &error.code });
28 
29 Some((status, page).into_response())
30 });
31 })
1use laravel::inertia::props;
2use laravel::prelude::*;
3use serde_json::json;
4 
5#[derive(Debug, thiserror::Error)]
6#[error("Your card was declined.")]
7pub struct CardDeclined {
8 pub code: String,
9}
10 
11Application::configure()
12 .with_errors(|errors, _| {
13 errors
14 .status::<CardDeclined>(402)
15 .render(|error: &CardDeclined, request, status| {
16 if request.wants_json() {
17 let body = json!({
18 "message": error.to_string(),
19 "code": error.code,
20 });
21 
22 return Some((status, Json(body)).into_response());
23 }
24 
25 let page = request
26 .inertia()?
27 .render("Billing/CardDeclined", props! { code => &error.code });
28 
29 Some((status, page).into_response())
30 });
31 })

request.inertia() returns None on routes that don't run HandleInertiaRequests, so ? falls back to Laravel's default error rendering on those routes.

Expired pages

A request that fails CSRF protection receives a 419 Page Expired response. Modern browsers on HTTPS pass origin verification, but on plain HTTP or older browsers a user whose session expired while a form was open gets a 419. Because CSRF protection runs before HandleInertiaRequests, Laravel renders the built-in 419 page and Inertia's client displays it in a modal over the form.

For a smoother experience, redirect the user back to their form with a notice by registering a responder in src/app.rs:

1use laravel::prelude::*;
2 
3Application::configure()
4 .with_errors(|errors, _| {
5 errors.respond(|response, _error, request| {
6 if response.status() == 419 && request.header("X-Inertia").is_some() {
7 return Redirect::back()
8 .status(303)
9 .with("status", "The page expired. Please try again.")
10 .into_response();
11 }
12 
13 response
14 });
15 })
1use laravel::prelude::*;
2 
3Application::configure()
4 .with_errors(|errors, _| {
5 errors.respond(|response, _error, request| {
6 if response.status() == 419 && request.header("X-Inertia").is_some() {
7 return Redirect::back()
8 .status(303)
9 .with("status", "The page expired. Please try again.")
10 .into_response();
11 }
12 
13 response
14 });
15 })

Keep both the X-Inertia header check and the 303 status code:

  • Checking X-Inertia limits the redirect to Inertia visits so JSON clients still receive a 419 JSON response and cross-site form submissions still receive an error page.
  • Returning 303 instructs the browser to follow the redirect with a GET request. Because HandleInertiaRequests hasn't run yet, Laravel hasn't converted 302 to 303 for PUT, PATCH, or DELETE requests, and a 302 would repeat the original request method.

Because HandleInertiaRequests hasn't run yet, use Redirect::with to store the notice as session flash data. To display the notice, read status from the session in HandleInertiaRequests::share. The destination page receives the notice as props.status, not in its flash field:

1async fn share(&self, request: &Request) -> laravel::Result<Props> {
2 Ok(props! {
3 status => request.session()?.get::<String>("status"),
4 })
5}
1async fn share(&self, request: &Request) -> laravel::Result<Props> {
2 Ok(props! {
3 status => request.session()?.get::<String>("status"),
4 })
5}

History encryption

Inertia caches each page's props in the browser's history state so the back button can restore previous pages instantly without a server request. After a user logs out, however, someone pressing the back button could still see private pages from their session. To prevent this, enable history encryption in HandleInertiaRequests::configure:

1use laravel::inertia;
2 
3impl inertia::Middleware for HandleInertiaRequests {
4 fn configure(&self, config: inertia::Config) -> inertia::Config {
5 config.encrypt_history(true)
6 }
7}
1use laravel::inertia;
2 
3impl inertia::Middleware for HandleInertiaRequests {
4 fn configure(&self, config: inertia::Config) -> inertia::Config {
5 config.encrypt_history(true)
6 }
7}

Then call inertia::clear_history()? when the user logs out. Inertia discards its encryption key so the browser's back button can no longer decrypt previously visited pages.

If you only want to encrypt specific pages, leave configure unchanged and chain .encrypt_history(true) onto inertia::render:

1inertia::render("Billing/Invoices", props! { invoices }).encrypt_history(true)
1inertia::render("Billing/Invoices", props! { invoices }).encrypt_history(true)

History encryption relies on the browser's Web Crypto API, which is available only over HTTPS and on localhost.

Asset versioning

When you deploy new frontend assets, users with your application already open are still running older JavaScript. Inertia detects a version mismatch on their next visit and performs a full page reload so they pick up the new assets automatically.

By default, Laravel computes the asset version by hashing your Vite build manifest. If you'd like to supply your own asset version, override version on HandleInertiaRequests:

1use laravel::inertia;
2 
3impl inertia::Middleware for HandleInertiaRequests {
4 fn version(&self) -> Option<String> {
5 Some(env!("CARGO_PKG_VERSION").to_owned())
6 }
7}
1use laravel::inertia;
2 
3impl inertia::Middleware for HandleInertiaRequests {
4 fn version(&self) -> Option<String> {
5 Some(env!("CARGO_PKG_VERSION").to_owned())
6 }
7}

Server-side rendering

Without server-side rendering, a visitor's initial page load receives an empty root container until the browser downloads and executes your JavaScript bundle. Server-side rendering (SSR) renders that initial HTML on the server so browsers and search engines receive the complete markup immediately.

SSR is disabled by default. Enable it in .env:

1INERTIA_SSR=true
1INERTIA_SSR=true

During local development, Vite renders your pages on demand. In production, build the SSR bundle with npm run build:ssr and run the SSR server alongside your Laravel binary with node bootstrap/ssr/app.js. Make sure the bundle exists before starting your application, because outside debug mode Laravel checks for it only once on startup.

If the SSR server is unreachable or a page fails to render, Laravel falls back to normal client-side rendering automatically.

If you deploy to Laravel Cloud, Cloud can build and run your Inertia SSR server for you automatically with no extra server management.

Testing pages

In your HTTP tests, call assert_inertia() on a test response to assert against the rendered page component and props:

1use laravel::testing::prelude::*;
2 
3#[laravel::test]
4async fn the_user_page_shows_the_user(app: Application) {
5 app.get("/users/1")
6 .await
7 .assert_inertia()
8 .component("Users/Show")
9 .has("user")
10 .equals("user.name", "Taylor")
11 .missing("user.password");
12}
1use laravel::testing::prelude::*;
2 
3#[laravel::test]
4async fn the_user_page_shows_the_user(app: Application) {
5 app.get("/users/1")
6 .await
7 .assert_inertia()
8 .component("Users/Show")
9 .has("user")
10 .equals("user.name", "Taylor")
11 .missing("user.password");
12}

Prop paths support "dot" notation, such as user.name or users.0.name. Calling component(...) also verifies that a matching page file exists in resources/js/pages, so a misspelled component name fails the test.

Assertion Asserts
component(name), url(url), version(version) The page's component, URL, or asset version.
has(path), missing(path) That a prop exists, or doesn't.
has_any(&[..]) That at least one of the listed props exists.
equals(path, value) A prop's value (objects match regardless of key order).
satisfies(path, |value: T| ..) That a prop deserializes as T and satisfies the closure, such as |views: u64| views > 10.
contains(path, item) That a list item or object value equals item in full. For partial checks, use satisfies.
has_count(path, count), has_count_in(path, 1..=3) How many items a list or object prop contains.
deferred(group, &[..]) The props deferred in a group.
flash(path, value), has_flash(path), missing_flash(path) The page's flash data.
scope(path, ..), first(path, ..), each(path, ..) Props inside a nested object or list item, as Scoping assertions shows below.

Scoping assertions

To assert on a nested object, scope into it with scope. Paths inside the closure are relative to the scoped prop. Use first to scope into the first item of a list, and each to assert on every item in a list:

1app.get("/posts")
2 .await
3 .assert_inertia()
4 .has_count("posts", 2)
5 .first("posts", |post| {
6 post.equals("title", "Hello")
7 .satisfies("views", |views: u64| views > 10)
8 .scope("author", |author| author.equals("name", "Taylor").etc())
9 })
10 .each("posts", |post| post.has("id").missing("author.email").etc());
1app.get("/posts")
2 .await
3 .assert_inertia()
4 .has_count("posts", 2)
5 .first("posts", |post| {
6 post.equals("title", "Hello")
7 .satisfies("views", |views: u64| views > 10)
8 .scope("author", |author| author.equals("name", "Taylor").etc())
9 })
10 .each("posts", |post| post.has("id").missing("author.email").etc());

A scoped closure fails if any prop inside the scoped object goes unasserted, catching unexpected props that slip onto a page. Call etc() at the end of a scope when you want to allow remaining props without asserting on each of them.

Testing partial reloads

To test how a page behaves during a partial reload, reload the asserted page directly. reload_only requests only the specified props (matching router.reload({ only: [..] })), reload_except requests every prop except the listed ones, and reload reloads the entire page. Each reload reuses the original request's headers, cookies, and authenticated user:

1let page = app.get("/posts/1").await.assert_inertia();
2 
3page.missing("reviews");
4 
5page.reload_only(&["reviews"]).await.has_count("reviews", 3);
6 
7page.reload_except(&["reviews"]).await.has("post").missing("reviews");
1let page = app.get("/posts/1").await.assert_inertia();
2 
3page.missing("reviews");
4 
5page.reload_only(&["reviews"]).await.has_count("reviews", 3);
6 
7page.reload_except(&["reviews"]).await.has("post").missing("reviews");

To simulate the browser fetching deferred props after the initial render, call load_deferred_props, or call load_deferred_groups to load only specific deferred groups:

1let page = app.get("/dashboard").await.assert_inertia();
2 
3page.missing("stats").deferred("default", &["stats"]);
4 
5page.load_deferred_props().await.has("stats.visits");
6 
7page.load_deferred_groups(&["sidebar"]).await.has("teams");
1let page = app.get("/dashboard").await.assert_inertia();
2 
3page.missing("stats").deferred("default", &["stats"]);
4 
5page.load_deferred_props().await.has("stats.visits");
6 
7page.load_deferred_groups(&["sidebar"]).await.has("teams");