inertia

package module
v0.5.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 24 Imported by: 1

README

lemmego/inertia

Inertia.js for Lemmego applications: your routing, validation and data loading stay in Go, and a React or Vue component renders the page. No separate API to build.

A handler returns a component name and some props; Inertia decides whether the browser gets a full HTML document or just JSON for a client-side visit.

import "github.com/lemmego/inertia"

func Show(c app.Context) error {
    return inertia.Respond(c, "Posts/Show", map[string]any{
        "post": post,
    })
}

Install

go get github.com/lemmego/inertia

Register it

// bootstrap/providers.go
&inertia.Provider{
    Options: []inertia.Option{
        inertia.WithSSR(),
    },
},

RootTemplate defaults to resources/views/root.html, which is where lemmego new puts it.

Responding

Call What it does
inertia.Respond(c, "Posts/Show", props) render a component
inertia.Redirect(c, "/posts") redirect, with the status Inertia expects
inertia.Back(c) back to the referring page, for a failed form
inertia.Location(c, url) leave the SPA entirely — an external URL, or a sign-in page on another host

Redirect answers 303 for a PUT, PATCH or DELETE, because a browser following a 302 after one of those re-issues the original method. If you assert on the status in a test, assert 303 there.

Props

Everything in the map is sent on the first load. These wrappers change that:

Wrapper Sent
inertia.Optional(v) only when the client asks for it by name
inertia.Defer(v) after the page renders, in a second request
inertia.Always(v) on every response, including partial reloads
inertia.Once(v) on the initial load only
inertia.Merge(v) / DeepMerge(v) merged into the existing prop instead of replacing it — for an infinite list
inertia.Scroll(v, …) a paginated prop the client appends to while scrolling

Defer is the one to reach for when a page has one slow query and five fast ones. Optional is for data a page needs only sometimes, so a partial reload can ask for it by name.

Shared props, and the ordering trap
inertia.Get(a).ShareProp("appName", "Acme")

A shared prop is evaluated when you share it, so anything that depends on the current request has to be a closure:

inertia.SetProp(c.RequestContext(), "viewer", func() any {
    user, _ := auth.UserAs[*models.User](c)
    return viewerProps(user)
})

This matters more than it looks. Middleware is often prepended ahead of a route's own auth.OptionalAuth, so a shell or layout middleware that reads the user eagerly gets the signed-out answer on a signed-in request — silently, because a page that renders is a page nobody investigates. A closure is resolved after your auth middleware has run.

Flash and validation errors
ctx := inertia.SetValidationErrors(c.RequestContext(), errs)
ctx = inertia.SetFlashValue(ctx, "status", "Saved.")

Both ride the request context and survive the redirect, so a failed form re-renders with the messages attached.

Vite

inertia.WithVite(
    inertia.WithEntryPoints("resources/js/app.tsx"),
    inertia.WithBuildDir("public/build"),
)

In development the asset URLs come from ./public/hot, which the Vite dev server writes; in production they come from the build manifest.

A hot file in production is an error, not a fallback. You get ErrHotFileInProduction at boot, because the alternative is every asset URL on your live site pointing at localhost:5173 — a site that looks deployed and serves nothing.

Preloading is configurable: WithoutPreloading, WithWaterfallPreload(n), WithAggressivePreload, and WithIntegrity for subresource integrity hashes.

Server-side rendering

WithSSR() renders the page in Node before sending it, so a crawler, a link preview and a reader with JavaScript disabled all get real markup.

inertia.WithSSR()                           // resolve the renderer automatically
inertia.WithSSRAt("http://127.0.0.1:13714") // or point at it
inertia.WithoutSSR()                        // off, said out loud

INERTIA_SSR overrides all of them, so you can turn rendering off for an afternoon without editing LoadProviders and remembering to put it back:

INERTIA_SSR=false   # off, whatever the code says
INERTIA_SSR=true    # on — for checking a page really does render server-side
INERTIA_SSR=        # unset: the application decides

An unset or empty value means "as configured", and a value that is not a boolean means the same plus a warning — it will not take your process down.

In development the renderer is the Vite dev server — @inertiajs/vite serves /__inertia_ssr — so you do not start a separate process. In production, lemmego inertia-ssr runs the built bundle.

A renderer that has only just started answers 200 with the body null for a second or two, because Vite transforms the SSR entry lazily. So the first page you open after lemmego dev comes up has no server-rendered marker through no fault of its own. A document render is retried once before it counts as a fallback, which turns that into one slow page rather than a 500 — strict mode only, since outside it the fallback is already going out.

A failed render is the failure you have to go looking for

Inertia's own behaviour on an SSR error is to fall back to client rendering. The response is 200 and looks perfect to a person, while a crawler receives an empty <div id="app"> — and every meta tag rendered by your page component disappears with it.

So this package counts and reports it:

inertia.SSRFailures()   // cumulative fallbacks in this process

Outside production a failed render answers 500 with the reason instead, which is StrictSSR and is on by default. Turn it off with WithStrictSSR(false) if you need the degraded page locally.

Two things follow for your page components:

  • Never touch a browser global during render. window, document and localStorage do not exist in the renderer, and reading window.location.search while rendering throws. Put it in an effect, which never runs in Node.
  • Render your <title> and meta tags in Go, not in the page component. On the fallback path the component's head output is gone, which is exactly the failure you cannot see. lemmego/seo does this. Inertia's <Head title> would then emit a second <title>, so use a client-only effect if you want the tab title to update during a client-side visit.
Health checks
health := inertia.Get(a).CheckSSR(ctx)

SSRHealth has two levels. A shallow probe establishes that the renderer is alive. A deep one renders a real page and requires server-rendered markup back:

inertia.WithSSRProbeComponent("Health/Probe")

A deep probe needs a component that takes no props, because a real page handed empty props throws — and a probe that fails against a healthy renderer is worse than no probe. Add a page that exists for nothing else.

Register the check as non-critical unless your site is useless without SSR: a readiness probe failing on the renderer pulls every instance out of rotation for a site that still serves pages.

Testing

Assertable reads a response body as an Inertia page, so you assert on props rather than on rendered HTML:

page := inertia.AssertFromBytes(t, resp.Body.Bytes())
page.AssertComponent("Posts/Show")
page.AssertProps(map[string]any{"post": …})

Assert on props and not on strings in the markup. A substring check against rendered React is fragile — static text beside an interpolated value comes out as Continue with <!-- -->GitHub, because React inserts a comment marker — and a check against the whole document passes for any query whose text appears anywhere in it.

lemmego/apptest wires this up for you, including the asset version, without which every Inertia test gets a 409.

go test ./...
GOWORK=off go test ./...   # as a published module

Documentation

Index

Constants

View Source
const EnvSSR = "INERTIA_SSR"

ServerRenderedMarker is what a server-rendered document contains.

Its absence from a document response is the only reliable signal that the render fell back, and it is a better one than the log line the counter in ssr_health.go watches for: that depends on gonertia's wording, which is somebody else's string literal, and it fires after the response has already been decided. This is our own output. EnvSSR turns server-side rendering on or off, overriding what LoadProviders configured.

For the afternoon you want to work on a page without a renderer in the way, or the opposite — checking that a page really does render on the server before you ship it.

View Source
const EnvSSRURL = "INERTIA_SSR_URL"

EnvSSRURL points renders at a particular renderer, overriding both what LoadProviders configured and what the Vite hot file advertises.

This is how a development setup keeps server rendering *out* of the reload loop. Rendering through the Vite dev server means Vite transforms the SSR module graph on demand, so the first render after it starts is slow enough to look broken. The standalone renderer — `node bootstrap/ssr/ssr.js`, built by `vite build --ssr` — serves a bundle that was finished before it started, so it has no warm-up at all and nothing about rebuilding the Go binary touches it.

The cost is honest and worth stating: that bundle is only as current as the last `vite build --ssr`, so a component change shows up in the browser over HMR and *not* in the server-rendered document until it is rebuilt.

Setting this does not turn rendering on. INERTIA_SSR still decides that, so an address here and INERTIA_SSR=false together mean "off, and when it is on it is that renderer".

View Source
const InertiaBuildPath = "/public/build/"
View Source
const InertiaManifestPath = "./public/build/manifest.json"
View Source
const InertiaRootTemplatePath = "resources/views/root.html"
View Source
const ProbeComponent = "__inertia_probe__"

ProbeComponent is the component name a shallow probe asks for.

Deliberately one the bundle cannot have. See CheckSSR.

View Source
const ServerRenderedMarker = `data-server-rendered="true"`
View Source
const ViteHotPath = "./public/hot"

Variables

View Source
var ErrHotFileInProduction = fmt.Errorf(
	"inertia: %s exists in production; it points assets and server-side rendering at a Vite dev server. "+
		"Delete it — `lemmego build` does, and it belongs in .gitignore", ViteHotPath)

ErrHotFileInProduction is returned when a production process finds a Vite hot file.

It is the worst silent failure in the stack. detectSSRURL reads the hot file and points the renderer at a dev server that is not running, and viteTags points every asset at it too — so a production deploy serves a page whose CSS and JS 404 and whose markup is never server-rendered, with nothing in the logs about why. A stale ./public/hot committed or copied into an image is an easy mistake and a hard one to diagnose, so it is refused at boot instead.

View Source
var ErrSSRFellBack = errors.New(
	"inertia: server-side rendering is enabled but the document came back with no " +
		"server-rendered markup, which means the renderer failed and the page will be blank " +
		"until the client bundle takes over")

ErrSSRFellBack is returned by a document render that produced no server-rendered markup while server-side rendering was enabled.

Returned rather than logged-and-swallowed so the caller decides. In development that decision is a 500; in production it is a degraded page and a loud log.

Functions

func AddFlash added in v0.1.2

func AddFlash(ctx context.Context, flash Flash) context.Context

AddFlash appends flash data to the context.

func AddValidationErrors added in v0.1.2

func AddValidationErrors(ctx context.Context, errors ValidationErrors) context.Context

AddValidationErrors appends validation errors to the context.

func Back added in v0.1.2

func Back(c app.Context)

Back redirects the user to the previous URL via the registered Inertia instance.

func ClearHistory added in v0.1.2

func ClearHistory(ctx context.Context) context.Context

ClearHistory marks that history should be cleared on the next request.

func GetProps added in v0.1.2

func GetProps(ctx context.Context) map[string]any

GetProps retrieves props from the context.

func GetTemplateData added in v0.1.2

func GetTemplateData(ctx context.Context) map[string]any

GetTemplateData retrieves template data from the context.

func IsInertiaRequest added in v0.1.2

func IsInertiaRequest(r *http.Request) bool

IsInertiaRequest returns true if the request was made by the Inertia client.

func Location added in v0.1.2

func Location(c app.Context, url string, status ...int)

Location performs an external redirect via the registered Inertia instance.

func Redirect added in v0.1.2

func Redirect(c app.Context, url string)

Redirect performs a server-side redirect via the registered Inertia instance.

func Respond

func Respond(c app.Context, filePath string, props map[string]any) error

Respond renders an Inertia page response. Validation errors from the session are automatically merged into props.

func SSRFailures added in v0.1.10

func SSRFailures() uint64

SSRFailures returns how many server-side renders have fallen back since the process started.

Expose it on a readiness endpoint and alert on the rate. A non-zero and rising count means every page is being served without server-rendered markup, and nothing else in the stack will tell you.

func SetEncryptHistory added in v0.1.2

func SetEncryptHistory(ctx context.Context, encrypt ...bool) context.Context

SetEncryptHistory enables or disables history encryption for the next request.

func SetFlash added in v0.1.2

func SetFlash(ctx context.Context, flash Flash) context.Context

SetFlash stores flash data on the context for the next Inertia request.

func SetFlashValue added in v0.1.2

func SetFlashValue(ctx context.Context, key string, val any) context.Context

SetFlashValue stores a single flash value on the context.

func SetProp added in v0.1.2

func SetProp(ctx context.Context, key string, val any) context.Context

SetProp stores a single prop value on the context.

func SetProps added in v0.1.2

func SetProps(ctx context.Context, props map[string]any) context.Context

SetProps stores props on the context. Props set this way are merged into every page rendered during the request.

func SetStrictSSR added in v0.1.11

func SetStrictSSR(strict bool)

SetStrictSSR turns the hard failure on or off. Provider calls it.

func SetTemplateData added in v0.1.2

func SetTemplateData(ctx context.Context, data map[string]any) context.Context

SetTemplateData stores template data on the context. Values set this way are available in the root template.

func SetTemplateDatum added in v0.1.2

func SetTemplateDatum(ctx context.Context, key string, val any) context.Context

SetTemplateDatum stores a single template datum on the context.

func SetValidationError added in v0.1.2

func SetValidationError(ctx context.Context, key string, msg string) context.Context

SetValidationError stores a single validation error message on the context.

func SetValidationErrors added in v0.1.2

func SetValidationErrors(ctx context.Context, errors ValidationErrors) context.Context

SetValidationErrors stores validation errors on the context for the next Inertia request. Typically called before a Redirect.

func StrictSSR added in v0.1.11

func StrictSSR() bool

StrictSSR reports whether a fallback is currently a hard failure.

func Vite

func Vite(manifestPath, buildDir string) func(p string) (string, error)

Vite returns a template function that resolves Vite asset paths from a manifest file. Used when not leveraging gonertia's built-in Vite support.

Types

type AlwaysProp added in v0.1.2

type AlwaysProp struct {
	Value any
}

AlwaysProp is a property always included, even during partial reloads.

func Always added in v0.1.2

func Always(value any) AlwaysProp

Always creates an always-evaluated prop value.

func (AlwaysProp) Prop added in v0.1.2

func (p AlwaysProp) Prop() any

type Assertable added in v0.1.2

type Assertable struct {
	Body *bytes.Buffer
	// contains filtered or unexported fields
}

Assertable wraps an Inertia page response with assertion helpers for testing.

func AssertFromBytes added in v0.1.2

func AssertFromBytes(t T, body []byte) Assertable

AssertFromBytes parses an Inertia response bytes and returns an Assertable.

func AssertFromReader added in v0.1.2

func AssertFromReader(t T, body io.Reader) Assertable

AssertFromReader parses an Inertia response body and returns an Assertable.

func AssertFromString added in v0.1.2

func AssertFromString(t T, body string) Assertable

AssertFromString parses an Inertia response string and returns an Assertable.

func (Assertable) AssertClearHistory added in v0.1.2

func (a Assertable) AssertClearHistory(want bool)

AssertClearHistory verifies the clear history flag.

func (Assertable) AssertComponent added in v0.1.2

func (a Assertable) AssertComponent(want string)

AssertComponent verifies that the response component matches want.

func (Assertable) AssertDeferredProps added in v0.1.2

func (a Assertable) AssertDeferredProps(want map[string][]string)

AssertDeferredProps verifies the deferred props map.

func (Assertable) AssertEncryptHistory added in v0.1.2

func (a Assertable) AssertEncryptHistory(want bool)

AssertEncryptHistory verifies the encrypt history flag.

func (Assertable) AssertMergeProps added in v0.1.2

func (a Assertable) AssertMergeProps(want []string)

AssertMergeProps verifies the merge props list.

func (Assertable) AssertProps added in v0.1.2

func (a Assertable) AssertProps(want map[string]any)

AssertProps verifies that the response props match want.

func (Assertable) AssertURL added in v0.1.2

func (a Assertable) AssertURL(want string)

AssertURL verifies that the response URL matches want.

func (Assertable) AssertVersion added in v0.1.2

func (a Assertable) AssertVersion(want string)

AssertVersion verifies that the response version matches want.

func (Assertable) ClearHistory added in v0.1.2

func (a Assertable) ClearHistory() bool

ClearHistory returns the clear history flag.

func (Assertable) Component added in v0.1.2

func (a Assertable) Component() string

Component returns the page component name.

func (Assertable) DeepMergeProps added in v0.1.2

func (a Assertable) DeepMergeProps() []string

DeepMergeProps returns the deep merge props list.

func (Assertable) DeferredProps added in v0.1.2

func (a Assertable) DeferredProps() map[string][]string

DeferredProps returns the deferred props map.

func (Assertable) EncryptHistory added in v0.1.2

func (a Assertable) EncryptHistory() bool

EncryptHistory returns the encrypt history flag.

func (Assertable) MatchPropsOn added in v0.1.2

func (a Assertable) MatchPropsOn() []string

MatchPropsOn returns the match props on list.

func (Assertable) MergeProps added in v0.1.2

func (a Assertable) MergeProps() []string

MergeProps returns the merge props list.

func (Assertable) PrependProps added in v0.1.2

func (a Assertable) PrependProps() []string

PrependProps returns the prepend props list.

func (Assertable) Props added in v0.1.2

func (a Assertable) Props() map[string]any

Props returns the page props.

func (Assertable) ScrollProps added in v0.1.2

func (a Assertable) ScrollProps() map[string]map[string]any

ScrollProps returns the scroll props metadata as a generic map.

func (Assertable) URL added in v0.1.2

func (a Assertable) URL() string

URL returns the request URL.

func (Assertable) Version added in v0.1.2

func (a Assertable) Version() string

Version returns the asset version.

type Config added in v0.1.2

type Config struct {
	Version         string
	VersionFromFile string
	VersionFS       any // io/fs.FS
	VersionFSPath   string
	SSREnabled      bool
	SSRURL          string
	SSRHTTPClient   any // *http.Client
	// SSRTimeout bounds one server-side render. Zero means the per-renderer
	// defaults, which is almost always what you want: see defaultSSRTimeout
	// and viteSSRTimeout.
	SSRTimeout     time.Duration
	FlashProvider  FlashProvider
	ContainerID    string
	EncryptHistory bool
	JSONMarshaller JSONMarshaller
	Logger         Logger
	ViteEnabled    bool
	ViteCfg        *ViteConfig
	// StrictSSR overrides what a failed render does. Nil means "strict
	// outside production", which is the default and almost always right.
	StrictSSR *bool
	// SSRProbeComponent is a component CheckSSR renders to prove the
	// renderer produces documents. Empty means a shallow probe. See
	// CheckSSR.
	SSRProbeComponent string
}

Config captures all user-facing inertia options before being translated into gonertia options internally.

type DeferProp added in v0.1.2

type DeferProp struct {
	Value any
	Group string
	// contains filtered or unexported fields
}

DeferProp is a property evaluated after the page has loaded. https://inertiajs.com/deferred-props

func Defer added in v0.1.2

func Defer(value any, group ...string) DeferProp

Defer creates a deferred prop value that loads after the initial page render.

func (DeferProp) Merge added in v0.1.2

func (p DeferProp) Merge() DeferProp

Merge makes the deferred prop merge instead of overwrite on subsequent loads.

func (DeferProp) Prop added in v0.1.2

func (p DeferProp) Prop() any

type Flash

type Flash map[string]any

Flash contains arbitrary one-time data exposed as page.flash.

func GetFlash added in v0.1.2

func GetFlash(ctx context.Context) Flash

GetFlash retrieves flash data from the context.

type FlashProvider added in v0.1.2

type FlashProvider interface {
	FlashErrors(ctx context.Context, errors ValidationErrors) error
	GetErrors(ctx context.Context) (ValidationErrors, error)
	Flash(ctx context.Context, flash Flash) error
	GetFlash(ctx context.Context) (Flash, error)
	ShouldClearHistory(ctx context.Context) (bool, error)
	FlashClearHistory(ctx context.Context) error
}

FlashProvider defines the contract for persisting validation errors and flash data across redirects. Implementations store values keyed by session ID.

func NewFlash

func NewFlash() FlashProvider

NewFlash creates a new in-memory flash provider.

type Inertia

type Inertia struct {
	// contains filtered or unexported fields
}

Inertia wraps gonertia.Inertia so that the rest of the framework never imports gonertia directly.

func Get

func Get(a app.App) *Inertia

Get retrieves the registered Inertia instance from the app container.

func NewInertia

func NewInertia(a app.App, rootTemplatePath string, opts ...Option) *Inertia

NewInertia creates a new Inertia instance. It is retained for compatibility with the original API. New code should use NewInertiaWithError so setup failures can be handled explicitly. It returns nil when initialization fails; it never terminates the process.

func NewInertiaWithError added in v0.1.6

func NewInertiaWithError(a app.App, rootTemplatePath string, opts ...Option) (*Inertia, error)

NewInertiaWithError creates a new Inertia instance and returns any setup error. User-supplied Options are collected into a Config, then translated into gonertia options internally.

func (*Inertia) Back

func (i *Inertia) Back(c app.Context)

Back redirects the user to the previous URL.

func (*Inertia) CheckSSR added in v0.1.10

func (i *Inertia) CheckSSR(ctx context.Context) SSRHealth

CheckSSR probes the render endpoint.

It POSTs a page and reads the answer, rather than dialling the port. A Node process listening with a broken module graph passes a TCP check and fails every render, which is precisely the state this exists to catch — and the CLI's own health check dials the port, so it cannot see it.

There are two levels, and the difference is worth understanding before trusting the result.

**Shallow**, the default. The probe asks for ProbeComponent, a name the bundle cannot have, so the renderer is *expected* to refuse it — and a refusal with a body is the signal: the process is up, the module graph loaded, and the bundle's router ran far enough to decide the component does not exist. The status is not required to be 200, because a correct renderer answering this question says 500.

That is a real check and a shallow one. It cannot distinguish a renderer that fails only on unknown components from one that fails on all of them, which is the condition that matters most.

**Deep**, when the application sets WithSSRProbeComponent. The probe asks for a real page and requires 200 and server-rendered markup back, which proves the thing an operator actually wants to know: this renderer produces documents. It needs a component that renders with no props — a page built for the purpose — because a real page given empty props throws, and a probe that fails against a healthy renderer is worse than no probe.

Check the body before the status. A renderer that does not know the probe component legitimately answers 500, so a status-first check reports every healthy development renderer as unusable; a refusal carrying a body is proof the renderer is alive.

func (*Inertia) Location added in v0.1.2

func (i *Inertia) Location(c app.Context, url string, status ...int)

Location performs an external redirect. For Inertia requests it sends a 409 response with an X-Inertia-Location header; otherwise a standard HTTP redirect.

func (*Inertia) Middleware added in v0.1.2

func (i *Inertia) Middleware(next http.Handler) http.Handler

Middleware returns an HTTP middleware that handles Inertia request detection, version checks, flash data resolution, and response wrapping.

func (*Inertia) Redirect

func (i *Inertia) Redirect(c app.Context, url string)

Redirect performs a server-side redirect.

func (*Inertia) Respond

func (i *Inertia) Respond(c app.Context, filePath string, props map[string]any) error

Respond renders an Inertia page response for the given context.

func (*Inertia) ShareProp added in v0.1.2

func (i *Inertia) ShareProp(key string, val any)

ShareProp shares a prop globally across all pages.

func (*Inertia) ShareTemplateData added in v0.1.2

func (i *Inertia) ShareTemplateData(key string, val any)

ShareTemplateData makes a value available in the root template.

func (*Inertia) ShareTemplateFunc added in v0.1.2

func (i *Inertia) ShareTemplateFunc(key string, val any) error

ShareTemplateFunc makes a function available in the root template.

type InertiaResponse

type InertiaResponse struct {
	*Inertia
	// contains filtered or unexported fields
}

InertiaResponse implements the Renderer interface so it can be passed to app.Context.Render().

func (*InertiaResponse) Render

func (ir *InertiaResponse) Render(w io.Writer) error

Render satisfies the Renderer interface expected by app.Context.Render().

func (*InertiaResponse) ViewName added in v0.5.1

func (ir *InertiaResponse) ViewName() string

ViewName satisfies app.ViewNamer, so a render observer reports the component that was rendered rather than "*inertia.InertiaResponse" on every page — which is a count, not a view panel.

It deliberately does not say whether the render came back server-rendered. The SSR guard already owns that question, counts its failures and logs them (see ssr_guard.go), and a second source of truth for it is exactly the drift this repository keeps paying for.

type JSONMarshaller added in v0.1.2

type JSONMarshaller interface {
	Decode(r io.Reader, v any) error
	Marshal(v any) ([]byte, error)
}

JSONMarshaller defines the interface for custom JSON serialization used internally by the Inertia page rendering pipeline.

type Logger added in v0.1.2

type Logger interface {
	Printf(format string, v ...any)
	Println(v ...any)
}

Logger defines the interface for logging within the Inertia package.

type MergeProps added in v0.1.2

type MergeProps struct {
	Value any
	// contains filtered or unexported fields
}

MergeProps is a property whose value is merged with previous values instead of being overwritten. https://inertiajs.com/merging-props

func DeepMerge added in v0.1.2

func DeepMerge(value any) MergeProps

DeepMerge creates a deep-mergeable prop value.

func Merge added in v0.1.2

func Merge(value any) MergeProps

Merge creates a mergeable prop value.

func (MergeProps) Append added in v0.1.2

func (p MergeProps) Append(paths ...string) MergeProps

Append marks the prop as appended (additive merge).

func (MergeProps) DeepMerge added in v0.1.2

func (p MergeProps) DeepMerge() MergeProps

DeepMerge sets the prop to deep-merge on subsequent updates.

func (MergeProps) MatchOn added in v0.1.2

func (p MergeProps) MatchOn(keys ...string) MergeProps

MatchOn restricts the merge behavior to only re-run when the listed keys change.

func (MergeProps) Merge added in v0.1.2

func (p MergeProps) Merge() MergeProps

Merge sets the prop to merge (append) on subsequent updates.

func (MergeProps) Prepend added in v0.1.2

func (p MergeProps) Prepend(paths ...string) MergeProps

Prepend marks the prop as prepended.

func (MergeProps) Prop added in v0.1.2

func (p MergeProps) Prop() any

type OnceProp added in v0.1.2

type OnceProp struct {
	Value any
}

OnceProp is a property sent only on the first visit, not on partial reloads unless explicitly requested. https://inertiajs.com/docs/v2/data-props/once-props

func Once added in v0.1.2

func Once(value any) OnceProp

Once creates a once-only prop value.

func (OnceProp) Prop added in v0.1.2

func (p OnceProp) Prop() any

type Option added in v0.1.2

type Option interface {
	Apply(*Config)
}

Option configures the Inertia instance. Users pass these to NewInertia (or Provider). The implementation never exposes gonertia to the caller.

func WithContainerID added in v0.1.2

func WithContainerID(id string) Option

WithContainerID sets the root container element id (default "app").

func WithEncryptHistory added in v0.1.2

func WithEncryptHistory() Option

WithEncryptHistory enables global history encryption.

func WithFlashProvider added in v0.1.2

func WithFlashProvider(p FlashProvider) Option

WithFlashProvider sets a custom flash data provider.

func WithJSONMarshaller added in v0.1.2

func WithJSONMarshaller(m JSONMarshaller) Option

WithJSONMarshaller sets a custom JSON marshaller for Inertia page data.

func WithLogger added in v0.1.2

func WithLogger(l Logger) Option

WithLogger sets a custom logger for the Inertia instance.

func WithSSR added in v0.1.2

func WithSSR() Option

WithSSR enables server-side rendering with auto-detection. In development mode, the Vite dev server URL is auto-detected from the hot file. In production, defaults to http://127.0.0.1:13714.

INERTIA_SSR in the environment overrides this either way, so a developer can turn rendering off for an afternoon without editing LoadProviders. See Provider.Provide.

func WithSSRAt added in v0.1.2

func WithSSRAt(url string) Option

WithSSRAt enables server-side rendering at a custom URL.

func WithSSRHTTPClient added in v0.1.2

func WithSSRHTTPClient(client *http.Client) Option

WithSSRHTTPClient sets a custom HTTP client for SSR requests.

The client's transport is wrapped, not replaced: a render still resolves the renderer's address per request and still waits out a Vite warm-up. A client carrying its own Timeout keeps it, and that Timeout then caps the per-renderer budget — so leave it zero unless you mean to bound every renderer the same way, in which case WithSSRTimeout says so more clearly.

func WithSSRProbeComponent added in v0.1.11

func WithSSRProbeComponent(component string) Option

WithSSRProbeComponent names a page CheckSSR renders to probe the renderer.

It turns a shallow probe — "the renderer is alive" — into a deep one: "the renderer produces server-rendered documents". The component must render with no props at all, so it is a page written for the purpose rather than a real one, because a real page given empty props throws and a probe that fails against a healthy renderer is worse than no probe.

func WithSSRTimeout added in v0.4.0

func WithSSRTimeout(d time.Duration) Option

WithSSRTimeout bounds one server-side render, whichever renderer answers it.

The default is per renderer and is the better choice: three seconds for the standalone server, which serves a prebuilt bundle, and a minute for the Vite dev endpoint, which may still be transforming one. Naming a single number overrides that distinction, so name one only when you have measured your own.

func WithSSRURL added in v0.5.0

func WithSSRURL(url string) Option

WithSSRURL says *where* the renderer is without saying whether rendering is on, which WithSSRAt conflates.

The distinction earns its keep for the INERTIA_SSR_URL override: an address in the environment must not be able to switch rendering back on for somebody who turned it off with INERTIA_SSR=false.

An address set this way is also *pinned*: it beats the Vite hot file rather than losing to it, which is the whole point of being able to name the standalone renderer while a Vite dev server is running. See EnvSSRURL.

func WithStrictSSR added in v0.1.11

func WithStrictSSR(strict bool) Option

WithStrictSSR decides what a failed server-side render does.

Strict, a failed render is a 500. Not strict, it is the client-rendered fallback plus an error log and a counter. Left unset it is strict outside production — see ssr_guard.go for why that asymmetry is deliberate.

func WithVersion added in v0.1.2

func WithVersion(v string) Option

WithVersion sets the asset version by an arbitrary string.

func WithVersionFromFile added in v0.1.2

func WithVersionFromFile(path string) Option

WithVersionFromFile sets the asset version from a file's checksum.

func WithVersionFromFileFS added in v0.1.2

func WithVersionFromFileFS(fs any, path string) Option

WithVersionFromFileFS sets the asset version from a file checksum using an embedded filesystem (e.g. embed.FS).

func WithVite added in v0.1.2

func WithVite(opts ...ViteOption) Option

WithVite enables the full Vite integration with asset preloading, template helpers (viteAssets, viteRefresh, viteReactRefresh), and optional CSP support. When not used, a basic Vite setup (hot file + manifest resolution) is applied.

func WithoutSSR added in v0.3.0

func WithoutSSR() Option

WithoutSSR turns server-side rendering off.

Mostly for the INERTIA_SSR override to apply, but also useful directly: it says "off" at the call site, where leaving WithSSR out says nothing and reads like an omission.

Order matters — the last option wins — so this placed after WithSSR beats it.

type OptionalProp added in v0.1.2

type OptionalProp struct {
	Value any
}

OptionalProp is a property evaluated only when requested in a partial reload. https://inertiajs.com/partial-reloads

func Optional added in v0.1.2

func Optional(value any) OptionalProp

Optional creates an optional (lazy) prop value.

func (OptionalProp) Prop added in v0.1.2

func (p OptionalProp) Prop() any

type PreloadStrategy added in v0.1.2

type PreloadStrategy string

PreloadStrategy controls how Vite assets are preloaded.

const (
	PreloadNone       PreloadStrategy = "none"
	PreloadAggressive PreloadStrategy = "aggressive"
	PreloadWaterfall  PreloadStrategy = "waterfall"
)

type Provider

type Provider struct {
	// RootTemplate is the path to the root HTML template file.
	// Defaults to InertiaRootTemplatePath if empty.
	RootTemplate string
	// Options applied during initialization.
	Options []Option
}

Provider implements app.Provider and bootstraps the Inertia instance.

func (*Provider) Provide

func (p *Provider) Provide(a app.App) error

type SSRHealth added in v0.1.10

type SSRHealth struct {
	// Enabled is whether this process is configured to server-render at all.
	Enabled bool
	// URL is the render endpoint.
	URL string
	// OK is whether the render endpoint answered a probe.
	OK bool
	// Deep is whether the probe rendered a real page and got server-rendered
	// markup back, rather than only establishing that the renderer is alive.
	// See CheckSSR for the difference and why it matters.
	Deep bool
	// Component is what the probe asked the renderer for.
	Component string
	// Status is the render endpoint's HTTP status.
	Status int
	// Failures is the process's cumulative fallback count.
	Failures uint64
	// Err describes why a probe failed.
	Err string
}

SSRHealth is what a readiness check reports.

type ScrollMetadata added in v0.1.2

type ScrollMetadata struct {
	PageName     string
	PreviousPage any
	NextPage     any
	CurrentPage  any
}

ScrollMetadata holds pagination metadata for infinite scroll.

type ScrollOption added in v0.1.2

type ScrollOption func(*ScrollProp)

ScrollOption configures a ScrollProp.

func WithMetadata added in v0.1.2

func WithMetadata(metadata ScrollMetadata) ScrollOption

WithMetadata sets pagination metadata for the scroll prop.

func WithWrapper added in v0.1.2

func WithWrapper(wrapper string) ScrollOption

WithWrapper sets a custom wrapper key for the scroll prop (defaults to "data").

type ScrollProp added in v0.1.2

type ScrollProp struct {
	Value    any
	Wrapper  string
	Metadata ScrollMetadata
}

ScrollProp is a property for infinite scrolling / pagination. https://inertiajs.com/infinite-scroll

func Scroll added in v0.1.2

func Scroll(value any, opts ...ScrollOption) ScrollProp

Scroll creates a scroll prop for infinite scrolling.

func (ScrollProp) Prop added in v0.1.2

func (p ScrollProp) Prop() any

type T added in v0.1.2

type T interface {
	Helper()
	Fatal(args ...any)
	Fatalf(format string, args ...any)
}

T is the minimal interface for testing helpers.

type ValidationErrors added in v0.1.2

type ValidationErrors map[string]any

ValidationErrors holds validation error messages keyed by field name.

func GetValidationErrors added in v0.1.2

func GetValidationErrors(ctx context.Context) ValidationErrors

GetValidationErrors retrieves validation errors from the context.

type ViteConfig added in v0.1.2

type ViteConfig struct {
	HotFile           string
	BuildManifest     string
	FallbackManifest  string
	BuildDir          string
	HotReloadPort     string
	EntryPoints       []string
	IntegrityEnabled  bool
	PreloadStrategy   PreloadStrategy
	PreloadConcurrent int
	EmbedFS           any // fs.FS for embedded manifest loading
}

ViteConfig holds Vite-specific settings for the Inertia instance. Applied via WithVite().

type ViteOption added in v0.1.2

type ViteOption func(*ViteConfig)

ViteOption configures the Vite integration.

func WithAggressivePreload added in v0.1.2

func WithAggressivePreload() ViteOption

WithAggressivePreload preloads all dependencies immediately.

func WithBuildDir added in v0.1.2

func WithBuildDir(dir string) ViteOption

WithBuildDir sets the build output directory.

func WithBuildManifest added in v0.1.2

func WithBuildManifest(path string) ViteOption

WithBuildManifest sets the build manifest path.

func WithEntryPoints added in v0.1.2

func WithEntryPoints(entries ...string) ViteOption

WithEntryPoints sets the entry points for asset generation.

func WithFallbackManifest added in v0.1.2

func WithFallbackManifest(path string) ViteOption

WithFallbackManifest sets the fallback manifest path.

func WithHotFile added in v0.1.2

func WithHotFile(path string) ViteOption

WithHotFile sets the hot reload file path.

func WithHotReloadPort added in v0.1.2

func WithHotReloadPort(port string) ViteOption

WithHotReloadPort sets the hot reload server port.

func WithIntegrity added in v0.1.2

func WithIntegrity() ViteOption

WithIntegrity enables SubResource Integrity (requires vite-plugin).

func WithViteEmbedFS added in v0.1.2

func WithViteEmbedFS(fs any) ViteOption

WithViteEmbedFS sets an embed.FS for production builds.

func WithWaterfallPreload added in v0.1.2

func WithWaterfallPreload(concurrent int) ViteOption

WithWaterfallPreload enables batched prefetch with concurrency control.

func WithoutPreloading added in v0.1.2

func WithoutPreloading() ViteOption

WithoutPreloading disables asset preloading (default).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL