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 handlers/posts/posts.go loads a post and passes it to the Posts/Show component:

1package posts
2 
3import (
4 "go.laravel.com/inertia"
5 "go.laravel.com/model"
6 "go.laravel.com/web"
7 
8 "app/models"
9)
10 
11func Show(r *web.Request) *web.Response {
12 post, err := model.FromRoute[models.Post](r, "post")
13 if err != nil {
14 return web.Fail(err)
15 }
16 
17 return inertia.Render("Posts/Show", inertia.Props{"post": post})
18}
1package posts
2 
3import (
4 "go.laravel.com/inertia"
5 "go.laravel.com/model"
6 "go.laravel.com/web"
7 
8 "app/models"
9)
10 
11func Show(r *web.Request) *web.Response {
12 post, err := model.FromRoute[models.Post](r, "post")
13 if err != nil {
14 return web.Fail(err)
15 }
16 
17 return inertia.Render("Posts/Show", inertia.Props{"post": post})
18}

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, in the inertia package. New applications come set up with React, TypeScript, Tailwind, and Vite, and add 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 with the fields of inertia.Middleware, which new applications append to the web middleware group in bootstrap/app.go, after the authentication middleware. Every field is optional, so you only set what you need. By default, new applications share the application's name and the session's status value with every page, and render errors using the Error page component:

1package bootstrap
2 
3import (
4 laravel "go.laravel.com"
5 "go.laravel.com/auth"
6 "go.laravel.com/config"
7 "go.laravel.com/inertia"
8 "go.laravel.com/web"
9 
10 "app/models"
11 "app/resources"
12)
13 
14func Options() laravel.Options {
15 return laravel.Options{
16 // ...
17 Views: resources.Views,
18 Middleware: func(m *laravel.Middleware, cfg *config.Config) {
19 m.Web.Append(auth.Session[models.User]{})
20 m.Web.Append(inertia.Middleware{
21 Share: share,
22 ErrorPage: "Error",
23 })
24 },
25 }
26}
27 
28func share(r *web.Request) (inertia.Props, error) {
29 return inertia.Props{
30 "name": config.From(r).App.Name,
31 "status": r.Session().Get("status"),
32 }, nil
33}
1package bootstrap
2 
3import (
4 laravel "go.laravel.com"
5 "go.laravel.com/auth"
6 "go.laravel.com/config"
7 "go.laravel.com/inertia"
8 "go.laravel.com/web"
9 
10 "app/models"
11 "app/resources"
12)
13 
14func Options() laravel.Options {
15 return laravel.Options{
16 // ...
17 Views: resources.Views,
18 Middleware: func(m *laravel.Middleware, cfg *config.Config) {
19 m.Web.Append(auth.Session[models.User]{})
20 m.Web.Append(inertia.Middleware{
21 Share: share,
22 ErrorPage: "Error",
23 })
24 },
25 }
26}
27 
28func share(r *web.Request) (inertia.Props, error) {
29 return inertia.Props{
30 "name": config.From(r).App.Name,
31 "status": r.Session().Get("status"),
32 }, nil
33}

The other fields of inertia.Middleware customize the root view and asset version, and turn on history encryption for every page. AllErrors sends every validation message of a field rather than only the first. If your createInertiaApp call mounts the page in an element other than app, set RootID to the same id.

Inertia works only on routes that run inertia.Middleware. Calling inertia.Render on a route outside the web group, such as a route in routes/api.go, 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 {{viteReactRefresh}}
6 {{vite "resources/js/app.tsx" (print "resources/js/pages/" .Component ".tsx")}}
7 {{.Head}}
8 </head>
9 <body>
10 {{.Body}}
11 </body>
12</html>
1<!DOCTYPE html>
2<html lang="en">
3 <head>
4 <meta charset="utf-8">
5 {{viteReactRefresh}}
6 {{vite "resources/js/app.tsx" (print "resources/js/pages/" .Component ".tsx")}}
7 {{.Head}}
8 </head>
9 <body>
10 {{.Body}}
11 </body>
12</html>

The root view's data is an inertia.Root, which holds these fields:

In the root view What it renders
{{.Body}} The root element where Inertia mounts the page.
{{.Head}} The page's head metadata, followed by any other head tags that server-side rendering returns.
{{.Component}} The page component's name, such as Users/Show.
{{.Props}}, {{.URL}}, {{.Version}} The page's props, URL, and asset version.
{{.Data}} The data your handler passed with inertia.ViewData, as shown below.

The root view is a standard view, so it may call any of Laravel's helpers, such as vite, and it may use a layout. Sometimes the root view needs a value that the page component doesn't, such as a class on the <html> element for a dark theme. To pass data only to the root view for a single response without sending it as an Inertia prop, call inertia.ViewData before you render:

1func Dashboard(r *web.Request) *web.Response {
2 inertia.ViewData(r, "theme", "dark")
3 
4 return inertia.Render("Dashboard")
5}
1func Dashboard(r *web.Request) *web.Response {
2 inertia.ViewData(r, "theme", "dark")
3 
4 return inertia.Render("Dashboard")
5}

The root view reads the value from .Data, as in <html lang="en" class="{{.Data.theme}}">. An Inertia visit receives the page as JSON without the root view, so only a full page load uses .Data.

Outside debug mode, Laravel reads your Vite build once on startup, so restart your application after rebuilding your frontend assets.

Using another root view

To render a different template as your root view, set the RootView field of inertia.Middleware to the view's name:

1m.Web.Append(inertia.Middleware{
2 RootView: "layouts.inertia",
3 Share: share,
4 ErrorPage: "Error",
5})
1m.Web.Append(inertia.Middleware{
2 RootView: "layouts.inertia",
3 Share: share,
4 ErrorPage: "Error",
5})

Rendering pages

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

1package users
2 
3import (
4 "go.laravel.com/inertia"
5 "go.laravel.com/model"
6 "go.laravel.com/web"
7 
8 "app/models"
9)
10 
11func Show(r *web.Request) *web.Response {
12 user, err := model.FromRoute[models.User](r, "user")
13 if err != nil {
14 return web.Fail(err)
15 }
16 
17 return inertia.Render("Users/Show", inertia.Props{"user": user})
18}
1package users
2 
3import (
4 "go.laravel.com/inertia"
5 "go.laravel.com/model"
6 "go.laravel.com/web"
7 
8 "app/models"
9)
10 
11func Show(r *web.Request) *web.Response {
12 user, err := model.FromRoute[models.User](r, "user")
13 if err != nil {
14 return web.Fail(err)
15 }
16 
17 return inertia.Render("Users/Show", inertia.Props{"user": user})
18}

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, you may omit the props argument:

1return inertia.Render("Dashboard")
1return inertia.Render("Dashboard")

For pages whose props you want to type-check at compile time, define a struct with json tags and a Component() string method (satisfying inertia.Page), then return inertia.RenderPage. Struct fields may hold plain values or *inertia.Prop wrappers such as inertia.Defer, inertia.Lazy, or inertia.Optional:

1type ShowUserPage struct {
2 User models.User `json:"user"`
3 CanEdit bool `json:"canEdit"`
4 Posts *inertia.Prop `json:"posts"`
5 Activity *inertia.Prop `json:"activity"`
6}
7 
8func (ShowUserPage) Component() string { return "Users/Show" }
9 
10func Show(r *web.Request) *web.Response {
11 user, err := model.FromRoute[models.User](r, "user")
12 if err != nil {
13 return web.Fail(err)
14 }
15 
16 posts := model.Query[models.Post]().
17 WhereEq("user_id", user.ID).
18 Latest("created_at")
19 
20 activity := model.Query[models.Activity]().
21 WhereEq("user_id", user.ID).
22 Latest("created_at")
23 
24 return inertia.RenderPage(ShowUserPage{
25 User: user,
26 CanEdit: true,
27 Posts: inertia.Defer(posts.Get),
28 Activity: inertia.Lazy(activity.Get),
29 })
30}
1type ShowUserPage struct {
2 User models.User `json:"user"`
3 CanEdit bool `json:"canEdit"`
4 Posts *inertia.Prop `json:"posts"`
5 Activity *inertia.Prop `json:"activity"`
6}
7 
8func (ShowUserPage) Component() string { return "Users/Show" }
9 
10func Show(r *web.Request) *web.Response {
11 user, err := model.FromRoute[models.User](r, "user")
12 if err != nil {
13 return web.Fail(err)
14 }
15 
16 posts := model.Query[models.Post]().
17 WhereEq("user_id", user.ID).
18 Latest("created_at")
19 
20 activity := model.Query[models.Activity]().
21 WhereEq("user_id", user.ID).
22 Latest("created_at")
23 
24 return inertia.RenderPage(ShowUserPage{
25 User: user,
26 CanEdit: true,
27 Posts: inertia.Defer(posts.Get),
28 Activity: inertia.Lazy(activity.Get),
29 })
30}

If a page needs no handler logic at all, register it directly in routes/web.go with route.Inertia, giving it the URI and the component's name:

1route.Inertia("/about", "About")
1route.Inertia("/about", "About")

Props

inertia.Props is a map from each prop's name to its value, and a value may be anything that encodes to JSON, such as a model. To set a nested prop, write its key with dots, so "auth.permissions" becomes permissions inside auth:

1return inertia.Render("Users/Show", inertia.Props{
2 "user": user,
3 "canEdit": true,
4 "auth.permissions": []string{"users.edit"},
5})
1return inertia.Render("Users/Show", inertia.Props{
2 "user": user,
3 "canEdit": true,
4 "auth.permissions": []string{"users.edit"},
5})

Keys keep the exact casing you write, and they're the names your components read, so name props the way your frontend expects, which is usually camelCase.

To include a prop only sometimes, add it to the map in an if before you render:

1props := inertia.Props{"user": user}
2if user.EmailVerifiedAt == nil {
3 props["verificationNotice"] = "Please verify your email address."
4}
5 
6return inertia.Render("Users/Show", props)
1props := inertia.Props{"user": user}
2if user.EmailVerifiedAt == nil {
3 props["verificationNotice"] = "Please verify your email address."
4}
5 
6return inertia.Render("Users/Show", props)

A prop you don't add is omitted completely rather than sent as null, unlike a nil pointer, which the page receives as null.

Every prop is sent to the browser and visible to anyone inspecting the page. Send only what the page needs, and leave a struct's private fields out of its JSON with json:"-", as the User model in new applications does for its password and remember token.

JavaScript holds integers exactly only up to 9007199254740991, so the browser rounds a larger one, such as a 64-bit ID from another system, and a link built from it would point at the wrong record. If your props hold such integers, set PreserveBigIntegers: true on inertia.Middleware, or call inertia.PreserveBigIntegers(r) in a single page's handler. If PreserveBigIntegers is enabled globally, call inertia.PreserveBigIntegers(r, false) to turn it off for a specific page. Inertia's client then receives each of those integers as a BigInt, so type the prop as bigint in your component.

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:

1package users
2 
3import (
4 "go.laravel.com/inertia"
5 "go.laravel.com/model"
6 "go.laravel.com/web"
7 
8 "app/models"
9)
10 
11func Show(r *web.Request) *web.Response {
12 user, err := model.FromRoute[models.User](r, "user")
13 if err != nil {
14 return web.Fail(err)
15 }
16 
17 posts := model.Query[models.Post]().WhereEq("user_id", user.ID).Latest("created_at")
18 
19 return inertia.Render("Users/Show", inertia.Props{
20 "user": user,
21 "posts": inertia.Defer(posts.Get),
22 })
23}
1package users
2 
3import (
4 "go.laravel.com/inertia"
5 "go.laravel.com/model"
6 "go.laravel.com/web"
7 
8 "app/models"
9)
10 
11func Show(r *web.Request) *web.Response {
12 user, err := model.FromRoute[models.User](r, "user")
13 if err != nil {
14 return web.Fail(err)
15 }
16 
17 posts := model.Query[models.Post]().WhereEq("user_id", user.ID).Latest("created_at")
18 
19 return inertia.Render("Users/Show", inertia.Props{
20 "user": user,
21 "posts": inertia.Defer(posts.Get),
22 })
23}

A prop function takes a context.Context and returns a value and an error, so you may pass a query's Get method as it is. For other work, pass a function literal, as in inertia.Defer(func(ctx context.Context) (int, error) { ... }). Laravel runs prop functions after your handler returns, when the page renders, and passes them the request's context.

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, pass a group name as the second argument to inertia.Defer. If a prop function returns an error, the page fails as if your handler had passed the error to web.Fail. You may chain .Rescue() so a failing prop is reported and left out, and the other props in the request still load:

1"posts": inertia.Defer(posts.Get, "posts").Rescue(),
1"posts": inertia.Defer(posts.Get, "posts").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:

1func Show(r *web.Request) *web.Response {
2 post, err := model.FromRoute[models.Post](r, "post")
3 if err != nil {
4 return web.Fail(err)
5 }
6 
7 comments := model.Query[models.Comment]().WhereEq("post_id", post.ID)
8 
9 return inertia.Render("Posts/Show", inertia.Props{
10 "post": post,
11 "comments": inertia.Optional(comments.Get),
12 })
13}
1func Show(r *web.Request) *web.Response {
2 post, err := model.FromRoute[models.Post](r, "post")
3 if err != nil {
4 return web.Fail(err)
5 }
6 
7 comments := model.Query[models.Comment]().WhereEq("post_id", post.ID)
8 
9 return inertia.Render("Posts/Show", inertia.Props{
10 "post": post,
11 "comments": inertia.Optional(comments.Get),
12 })
13}

On the frontend, <WhenVisible> watches the element with an IntersectionObserver and requests the comments prop in a partial reload 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 types 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(fn) Evaluated only when the response includes the prop. A plain function in inertia.Props is lazy, too.
inertia.Optional(fn) 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. Chain .Prepend() to put new items first, .MatchOn("id") to replace items the page already has, or .AppendAt("data") to merge only the list inside a paginator. inertia.DeepMerge(value) merges at every depth.
inertia.Once(value) Resolved once and cached on the client. Chain .For(24 * time.Hour) to expire it after a duration, .Until(t) to expire it at a time.Time, or .Fresh(condition) to force a refresh when a condition is true.
inertia.Scroll(fn) Wraps a paginator for Inertia's <InfiniteScroll> component.

You may combine these with method calls, so inertia.Defer(fn).Merge() is a deferred prop that merges.

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 the Share function of inertia.Middleware so every page receives it alongside its own props. Share returns an error as well as the props, so it may query the database, and an error it returns fails the request as an error from your handler would. A page's own prop replaces a shared prop of the same name. Keep shared data lean, since every Inertia response carries it.

To share the logged-in user with every page, add "auth.user" to the share function in bootstrap/app.go with models.CurrentUser. Pages receive null for guests:

1func share(r *web.Request) (inertia.Props, error) {
2 return inertia.Props{
3 "name": config.From(r).App.Name,
4 "auth.user": models.CurrentUser(r),
5 }, nil
6}
1func share(r *web.Request) (inertia.Props, error) {
2 return inertia.Props{
3 "name": config.From(r).App.Name,
4 "auth.user": models.CurrentUser(r),
5 }, nil
6}

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:

1package bootstrap
2 
3import (
4 "context"
5 
6 "go.laravel.com/config"
7 "go.laravel.com/inertia"
8 "go.laravel.com/web"
9 
10 "app/models"
11)
12 
13func share(r *web.Request) (inertia.Props, error) {
14 return inertia.Props{
15 "name": config.From(r).App.Name,
16 "auth.user": models.CurrentUser(r),
17 "cartCount": inertia.Lazy(func(context.Context) (int, error) {
18 cart, _ := r.Session().Value[[]string]("cart")
19 
20 return len(cart), nil
21 }),
22 }, nil
23}
1package bootstrap
2 
3import (
4 "context"
5 
6 "go.laravel.com/config"
7 "go.laravel.com/inertia"
8 "go.laravel.com/web"
9 
10 "app/models"
11)
12 
13func share(r *web.Request) (inertia.Props, error) {
14 return inertia.Props{
15 "name": config.From(r).App.Name,
16 "auth.user": models.CurrentUser(r),
17 "cartCount": inertia.Lazy(func(context.Context) (int, error) {
18 cart, _ := r.Session().Value[[]string]("cart")
19 
20 return len(cart), nil
21 }),
22 }, nil
23}

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.

Sometimes a prop belongs only on a group of routes, such as the active team on routes under /teams/{team}. Rather than checking the route inside bootstrap/app.go, call inertia.Share from that group's middleware or from a handler:

1func ShareTeam(r *web.Request, next web.Next) *web.Response {
2 team, err := model.FromRoute[models.Team](r, "team")
3 if err != nil {
4 return web.Fail(err)
5 }
6 
7 inertia.Share(r, "team", team)
8 
9 return next(r)
10}
1func ShareTeam(r *web.Request, next web.Next) *web.Response {
2 team, err := model.FromRoute[models.Team](r, "team")
3 if err != nil {
4 return web.Fail(err)
5 }
6 
7 inertia.Share(r, "team", team)
8 
9 return next(r)
10}

Props shared with inertia.Share follow the same rules as Middleware.Share: a page's own prop replaces a shared prop of the same name, and dotted keys such as "auth.can" merge into a shared object.

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 r.IsPrefetch() in your handler to skip side effects such as incrementing a page view counter:

1if !r.IsPrefetch() {
2 // Count the view...
3}
1if !r.IsPrefetch() {
2 // Count the view...
3}

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 the validation errors.

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 r.Validate, saves the record, and returns a redirect:

1package posts
2 
3import (
4 "go.laravel.com/auth"
5 "go.laravel.com/model"
6 "go.laravel.com/validation"
7 "go.laravel.com/validation/rule"
8 "go.laravel.com/web"
9 
10 "app/models"
11)
12 
13type StorePost struct {
14 Title string `json:"title"`
15 Body string `json:"body"`
16}
17 
18func (StorePost) Authorize(r *web.Request) error {
19 return auth.Authenticated(r)
20}
21 
22func (f *StorePost) Rules() validation.Rules {
23 return validation.For(f,
24 rule.Field(&f.Title, rule.Required, rule.Max(255)),
25 rule.Field(&f.Body, rule.Required),
26 )
27}
28 
29func Store(r *web.Request) *web.Response {
30 form, err := r.Validate[StorePost]()
31 if err != nil {
32 return web.Fail(err)
33 }
34 
35 post := models.Post{UserID: models.CurrentUser(r).ID, Title: form.Title, Body: form.Body}
36 if err := model.Create(r, &post); err != nil {
37 return web.Fail(err)
38 }
39 
40 return web.RedirectRoute("posts.show", "post", post.ID)
41}
1package posts
2 
3import (
4 "go.laravel.com/auth"
5 "go.laravel.com/model"
6 "go.laravel.com/validation"
7 "go.laravel.com/validation/rule"
8 "go.laravel.com/web"
9 
10 "app/models"
11)
12 
13type StorePost struct {
14 Title string `json:"title"`
15 Body string `json:"body"`
16}
17 
18func (StorePost) Authorize(r *web.Request) error {
19 return auth.Authenticated(r)
20}
21 
22func (f *StorePost) Rules() validation.Rules {
23 return validation.For(f,
24 rule.Field(&f.Title, rule.Required, rule.Max(255)),
25 rule.Field(&f.Body, rule.Required),
26 )
27}
28 
29func Store(r *web.Request) *web.Response {
30 form, err := r.Validate[StorePost]()
31 if err != nil {
32 return web.Fail(err)
33 }
34 
35 post := models.Post{UserID: models.CurrentUser(r).ID, Title: form.Title, Body: form.Body}
36 if err := model.Create(r, &post); err != nil {
37 return web.Fail(err)
38 }
39 
40 return web.RedirectRoute("posts.show", "post", post.ID)
41}

If validation fails, Laravel redirects back 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 with r.Validate, and pass its error to web.Fail. When validation fails, Laravel redirects back and populates the page's errors prop with each field's first message, such as {"title": "The title field is required."}, so Inertia's form helpers display each field's error.

If your form shows every problem with a field at once, such as each rule a new password breaks, set AllErrors: true on inertia.Middleware. Each field then holds a list of its messages, so type errors as lists of strings on the page.

If your handler detects an error that validation rules didn't catch, such as a name that is already taken, return web.Invalid with the field and its message. Laravel redirects back and populates the errors prop:

1return web.Invalid("name", "This name is already in use.")
1return web.Invalid("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:

1func Store(r *web.Request) *web.Response {
2 // Create the user...
3 
4 inertia.Flash(r, "toast", "User created!")
5 
6 return web.Back()
7}
1func Store(r *web.Request) *web.Response {
2 // Create the user...
3 
4 inertia.Flash(r, "toast", "User created!")
5 
6 return web.Back()
7}

The flashed value may be anything that encodes to JSON. To flash data onto a page you are rendering directly, call inertia.Flash before inertia.Render:

1inertia.Flash(r, "toast", "Welcome back!")
2 
3return inertia.Render("Users/Index", inertia.Props{"users": users})
1inertia.Flash(r, "toast", "Welcome back!")
2 
3return inertia.Render("Users/Index", inertia.Props{"users": users})

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 web.Redirect as usual. After a PUT, PATCH, or DELETE request, inertia.Middleware converts 302 redirects into 303 so the browser follows the redirect with a GET request.

Because an Inertia 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:

1func Billing(r *web.Request) *web.Response {
2 return inertia.Location("https://billing.stripe.com/p/session/test_123")
3}
1func Billing(r *web.Request) *web.Response {
2 return inertia.Location("https://billing.stripe.com/p/session/test_123")
3}

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 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 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 the event to its Live method. The prop listens on every channel that the event's BroadcastOn returns:

1package orders
2 
3import (
4 "context"
5 "fmt"
6 
7 "go.laravel.com/broadcast"
8 "go.laravel.com/inertia"
9 "go.laravel.com/model"
10 "go.laravel.com/web"
11 
12 "app/models"
13)
14 
15type OrderUpdated struct {
16 OrderID int64 `json:"order_id"`
17}
18 
19func (e OrderUpdated) BroadcastOn() []broadcast.Channel {
20 return []broadcast.Channel{broadcast.Private(fmt.Sprintf("orders.%d", e.OrderID))}
21}
22 
23func Show(r *web.Request) *web.Response {
24 id, err := r.PathInt("order")
25 if err != nil {
26 return web.Fail(err)
27 }
28 
29 return inertia.Render("Orders/Show", inertia.Props{
30 "order": inertia.Lazy(func(ctx context.Context) (models.Order, error) {
31 return model.Find[models.Order](ctx, id)
32 }).Live(OrderUpdated{OrderID: id}),
33 })
34}
1package orders
2 
3import (
4 "context"
5 "fmt"
6 
7 "go.laravel.com/broadcast"
8 "go.laravel.com/inertia"
9 "go.laravel.com/model"
10 "go.laravel.com/web"
11 
12 "app/models"
13)
14 
15type OrderUpdated struct {
16 OrderID int64 `json:"order_id"`
17}
18 
19func (e OrderUpdated) BroadcastOn() []broadcast.Channel {
20 return []broadcast.Channel{broadcast.Private(fmt.Sprintf("orders.%d", e.OrderID))}
21}
22 
23func Show(r *web.Request) *web.Response {
24 id, err := r.PathInt("order")
25 if err != nil {
26 return web.Fail(err)
27 }
28 
29 return inertia.Render("Orders/Show", inertia.Props{
30 "order": inertia.Lazy(func(ctx context.Context) (models.Order, error) {
31 return model.Find[models.Order](ctx, id)
32 }).Live(OrderUpdated{OrderID: id}),
33 })
34}

In your application, OrderUpdated would live in your events package with your other events, as the later examples on this page assume. Live only reads the event's channels and name, and doesn't broadcast the event. To refresh a prop in response to several events, pass each event to Live. Live props may also be Defer, Optional, Once, or Always, and inertia.Live(value, event) makes a plain value live, though merging 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. If your application uses an earlier client, update it first:

1npm install @inertiajs/react@^3.11.0 @inertiajs/vite@^3.11.0
1npm install @inertiajs/react@^3.11.0 @inertiajs/vite@^3.11.0

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 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, pass the channel and the event to LiveOn. The event's zero value is enough, because LiveOn only reads the event's name:

1"orders": inertia.Defer(model.Query[models.Order]().Latest("id").Get).
2 LiveOn(broadcast.Private("orders"), events.OrderUpdated{}),
1"orders": inertia.Defer(model.Query[models.Order]().Latest("id").Get).
2 LiveOn(broadcast.Private("orders"), events.OrderUpdated{}),

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. The client coalesces the events it receives during the interval into a single refresh:

1"orders": inertia.Defer(model.Query[models.Order]().Latest("id").Get).
2 LiveOn(broadcast.Private("orders"), events.OrderUpdated{}).
3 Throttle(5 * time.Second),
1"orders": inertia.Defer(model.Query[models.Order]().Latest("id").Get).
2 LiveOn(broadcast.Private("orders"), events.OrderUpdated{}).
3 Throttle(5 * time.Second),

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, give the event a BroadcastProps method that returns the new values, keyed by prop name:

1type OrderUpdated struct {
2 OrderID int64 `json:"order_id"`
3 Status string `json:"status"`
4}
5 
6func (e OrderUpdated) BroadcastOn() []broadcast.Channel {
7 return []broadcast.Channel{broadcast.Private(fmt.Sprintf("orders.%d", e.OrderID))}
8}
9 
10func (e OrderUpdated) BroadcastProps() any {
11 return map[string]any{"order": map[string]any{"id": e.OrderID, "status": e.Status}}
12}
1type OrderUpdated struct {
2 OrderID int64 `json:"order_id"`
3 Status string `json:"status"`
4}
5 
6func (e OrderUpdated) BroadcastOn() []broadcast.Channel {
7 return []broadcast.Channel{broadcast.Private(fmt.Sprintf("orders.%d", e.OrderID))}
8}
9 
10func (e OrderUpdated) BroadcastProps() any {
11 return map[string]any{"order": map[string]any{"id": e.OrderID, "status": e.Status}}
12}

Inertia's client updates those props directly in the browser without making an extra HTTP request. A listening prop that the event carries no value for refreshes with a partial reload as usual. To learn more about the event's payload, check out the broadcasting guide's section on custom broadcasts.

Inertia's client sends the page's socket ID on every request, so broadcasting the event with a context from broadcast.ToOthers skips refreshing the tab that triggered the change.

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 with 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. Name a page component in the ErrorPage field of inertia.Middleware to render errors with that Inertia component, as new applications do with ErrorPage: "Error" in bootstrap/app.go:

1m.Web.Append(inertia.Middleware{
2 Share: share,
3 ErrorPage: "Error",
4})
1m.Web.Append(inertia.Middleware{
2 Share: share,
3 ErrorPage: "Error",
4})

Your Error component in resources/js/pages/Error.tsx receives your shared props and an error prop holding the error's status and the message to show, such as {"status": 404, "message": "Not Found"}. The message is the status's reason phrase, except on a 403, where it's the error's message, such as a policy's denial. Requests that expect JSON still receive JSON, and server errors in debug mode still display the debug page.

On routes that run inertia.Middleware, this component replaces your HTML error views. Because an unmatched URL doesn't run route middleware, new applications end routes/web.go with a fallback route so 404 pages render through your Inertia Error component as well:

1route.Fallback(func(*web.Request) *web.Response {
2 return web.Abort(http.StatusNotFound)
3})
1route.Fallback(func(*web.Request) *web.Response {
2 return web.Abort(http.StatusNotFound)
3})

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, give the error type a Respond method that renders the page. Laravel sends the response that Respond builds instead of rendering your Error component:

1type CardDeclined struct {
2 Code string
3}
4 
5func (e *CardDeclined) Error() string {
6 return "Your card was declined."
7}
8 
9func (e *CardDeclined) Respond(r *web.Request) *web.Response {
10 return inertia.Render("Billing/CardDeclined", inertia.Props{"code": e.Code}).
11 WithStatus(http.StatusPaymentRequired)
12}
1type CardDeclined struct {
2 Code string
3}
4 
5func (e *CardDeclined) Error() string {
6 return "Your card was declined."
7}
8 
9func (e *CardDeclined) Respond(r *web.Request) *web.Response {
10 return inertia.Render("Billing/CardDeclined", inertia.Props{"code": e.Code}).
11 WithStatus(http.StatusPaymentRequired)
12}

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 inertia.Middleware, 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. Write a function like finishError below, and set it as the Respond function of the Errors option in bootstrap/app.go, as in Errors: web.Errors{Respond: finishError}:

1func finishError(r *web.Request, res *web.Response, err error) *web.Response {
2 if res.Status == 419 && r.Header.Get("X-Inertia") != "" {
3 return web.Back().
4 WithStatus(http.StatusSeeOther).
5 With("status", "The page expired. Please try again.")
6 }
7 
8 return res
9}
1func finishError(r *web.Request, res *web.Response, err error) *web.Response {
2 if res.Status == 419 && r.Header.Get("X-Inertia") != "" {
3 return web.Back().
4 WithStatus(http.StatusSeeOther).
5 With("status", "The page expired. Please try again.")
6 }
7 
8 return res
9}

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 inertia.Middleware 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.

The redirect uses With to store the notice as session flash data. To display the notice, read status from the session in your share function. The destination page receives the notice as props.status, not in its flash field:

1func share(r *web.Request) (inertia.Props, error) {
2 return inertia.Props{
3 // The application's name and user...
4 "status": r.Session().Get("status"),
5 }, nil
6}
1func share(r *web.Request) (inertia.Props, error) {
2 return inertia.Props{
3 // The application's name and user...
4 "status": r.Session().Get("status"),
5 }, nil
6}

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, set EncryptHistory on inertia.Middleware in bootstrap/app.go:

1m.Web.Append(inertia.Middleware{
2 Share: share,
3 ErrorPage: "Error",
4 EncryptHistory: true,
5})
1m.Web.Append(inertia.Middleware{
2 Share: share,
3 ErrorPage: "Error",
4 EncryptHistory: true,
5})

Then call inertia.ClearHistory(r) in the handler that logs the user 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, such as billing pages, leave EncryptHistory off and call inertia.EncryptHistory(r) in those pages' handlers:

1inertia.EncryptHistory(r)
2 
3return inertia.Render("Billing/Invoices", inertia.Props{"invoices": invoices})
1inertia.EncryptHistory(r)
2 
3return inertia.Render("Billing/Invoices", inertia.Props{"invoices": invoices})

If you enable EncryptHistory globally on inertia.Middleware, you may opt an individual page out by passing false:

1inertia.EncryptHistory(r, false)
2 
3return inertia.Render("Pricing")
1inertia.EncryptHistory(r, false)
2 
3return inertia.Render("Pricing")

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.

By default, Laravel computes the asset version by hashing your Vite build manifest, so most applications don't need to change it. If you'd like to supply your own asset version, such as your release's Git commit, return it from the Version function of inertia.Middleware:

1m.Web.Append(inertia.Middleware{
2 Share: share,
3 ErrorPage: "Error",
4 Version: func(r *web.Request) string { return os.Getenv("RELEASE") },
5})
1m.Web.Append(inertia.Middleware{
2 Share: share,
3 ErrorPage: "Error",
4 Version: func(r *web.Request) string { return os.Getenv("RELEASE") },
5})

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 while npm run dev runs. In production, build the SSR bundle with npm run build:ssr and run the SSR server alongside your application with node bootstrap/ssr/app.js. Laravel sends each page to the SSR server at http://127.0.0.1:13714. If your SSR server runs elsewhere, set INERTIA_SSR_URL to its address.

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

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

Testing pages

In your HTTP tests, call AssertInertia on a test response to assert against the rendered page component, and AssertProp to assert against its props:

1package feature_test
2 
3import (
4 "fmt"
5 "testing"
6 
7 "app/database/factories"
8 "app/models"
9 "app/tests"
10)
11 
12func TestTheUserPageShowsTheUser(t *testing.T) {
13 client := tests.New(t)
14 
15 user := client.Create(factories.User, func(u *models.User) { u.Name = "Taylor" })
16 
17 client.Get(fmt.Sprintf("/users/%d", user.ID)).
18 AssertOK().
19 AssertInertia("Users/Show").
20 AssertProp("user.name", "Taylor").
21 AssertPropMissing("user.password")
22}
1package feature_test
2 
3import (
4 "fmt"
5 "testing"
6 
7 "app/database/factories"
8 "app/models"
9 "app/tests"
10)
11 
12func TestTheUserPageShowsTheUser(t *testing.T) {
13 client := tests.New(t)
14 
15 user := client.Create(factories.User, func(u *models.User) { u.Name = "Taylor" })
16 
17 client.Get(fmt.Sprintf("/users/%d", user.ID)).
18 AssertOK().
19 AssertInertia("Users/Show").
20 AssertProp("user.name", "Taylor").
21 AssertPropMissing("user.password")
22}

Prop paths support "dot" notation, such as user.name or users.0.name. AssertProp compares the prop with the JSON your expected value encodes to, so you may pass a struct, a map, or a slice. AssertInertia also verifies that a matching page file exists in resources/js/pages, so a misspelled component name fails the test.

Assertion Asserts
AssertInertia(component) The page's component.
AssertProp(path, want), AssertPropMissing(path) A prop's value, or that the page doesn't have the prop.
AssertDeferred(props...) That the page loads each prop after it renders.
AssertFlash(path, want) The page's flash data.
AssertInertiaMatches(check) The props, with the fluent JSON assertions, as Scoping assertions shows below.
AssertTitle(text), AssertMeta(name, content) The page's head metadata.

Sometimes a test needs a prop's value for its next step, such as an invite link to follow. Decode the prop directly with Prop[T], or decode the page's flash data with Flash[T], such as a new API token that the page shows only once:

1link := client.Get("/events/7").AssertOK().Prop[string]("inviteLink")
2 
3client.Get(link).AssertOK()
1link := client.Get("/events/7").AssertOK().Prop[string]("inviteLink")
2 
3client.Get(link).AssertOK()

Scoping assertions

To assert on nested props, pass a function to AssertInertiaMatches, and scope into a nested object with Scope. Paths inside the function 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:

1client.Get("/posts").AssertInertia("Posts/Index").AssertInertiaMatches(func(props *webtest.JSON) {
2 props.Count("posts", 2).
3 First("posts", func(post *webtest.JSON) {
4 post.Equals("title", "Hello").
5 Where("views", func(views int) bool { return views > 10 }).
6 Scope("author", func(author *webtest.JSON) { author.Equals("name", "Taylor").Etc() })
7 }).
8 Each("posts", func(post *webtest.JSON) { post.Has("id").Missing("author.email").Etc() })
9})
1client.Get("/posts").AssertInertia("Posts/Index").AssertInertiaMatches(func(props *webtest.JSON) {
2 props.Count("posts", 2).
3 First("posts", func(post *webtest.JSON) {
4 post.Equals("title", "Hello").
5 Where("views", func(views int) bool { return views > 10 }).
6 Scope("author", func(author *webtest.JSON) { author.Equals("name", "Taylor").Etc() })
7 }).
8 Each("posts", func(post *webtest.JSON) { post.Has("id").Missing("author.email").Etc() })
9})

A scoped function fails if any prop inside the scoped object goes unasserted, catching unexpected props that slip onto a page, such as a user's email address on a public list. Call Etc at the end of a scope when you want to allow remaining props without asserting on each of them. At the top level, you may leave props unchecked, such as errors and the props that every page shares.

Testing partial reloads

To test how a page behaves during a partial reload, reload the asserted page directly. ReloadOnly requests only the specified props, matching router.reload({ only: [...] }), ReloadExcept requests every prop except the listed ones, and Reload reloads the entire page. Each reload sends the test client's cookies and logged-in user:

1page := client.Get("/posts/1").AssertPropMissing("reviews")
2 
3page.ReloadOnly("reviews").AssertProp("reviews.0.rating", 5)
4 
5page.ReloadExcept("reviews").AssertProp("post.id", 1).AssertPropMissing("reviews")
1page := client.Get("/posts/1").AssertPropMissing("reviews")
2 
3page.ReloadOnly("reviews").AssertProp("reviews.0.rating", 5)
4 
5page.ReloadExcept("reviews").AssertProp("post.id", 1).AssertPropMissing("reviews")

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

1page := client.Get("/dashboard").AssertDeferred("stats").AssertPropMissing("stats")
2 
3page.LoadDeferredProps().AssertProp("stats.visits", 120)
4 
5page.LoadDeferredGroups("sidebar").AssertProp("teams.0.name", "Laravel")
1page := client.Get("/dashboard").AssertDeferred("stats").AssertPropMissing("stats")
2 
3page.LoadDeferredProps().AssertProp("stats.visits", 120)
4 
5page.LoadDeferredGroups("sidebar").AssertProp("teams.0.name", "Laravel")