inertia

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: May 10, 2026 License: MIT Imports: 21 Imported by: 0

README

go-inertia

A small server-side Inertia.js adapter for Go.

The core package is built on net/http and has no runtime dependencies outside the Go standard library. Echo v5 support lives in a separate adapter module.

Status

This project is in the v0 release line. Check the Git tags for available versions.

The documentation and example application target Inertia.js 3.x client packages. go-inertia implements the protocol pieces listed below, but it is not a complete replacement for the official Laravel adapter.

Package Layout

  • github.com/mayahiro/go-inertia is the framework-independent core package.
  • github.com/mayahiro/go-inertia/adapters/echo adapts the core renderer to Echo v5.
  • examples/echo-react-vite is a separate example application module.

Requirements

  • Core package: Go 1.25.0 or newer
  • Echo adapter: Go 1.25.0 or newer, because Echo v5 requires it
  • Example frontend: Node.js 24 or newer

Installation

go get github.com/mayahiro/go-inertia

For Echo v5:

go get github.com/mayahiro/go-inertia/adapters/echo

What This Package Provides

  • HTML first-visit responses
  • Inertia JSON responses
  • Vary: X-Inertia
  • asset version mismatch handling
  • Inertia redirects, back redirects, and external locations
  • server-side shared props
  • flash data and validation error interfaces
  • single-process in-memory flash store
  • top-level partial reload filtering
  • lazy, optional, and always props
  • deferred props
  • once props
  • merge, prepend, and deep merge props
  • composable deferred, once, and merge prop modifiers
  • infinite scroll props
  • Precognition request and response helpers
  • history encryption and clear-history flags
  • prefetch request detection
  • Vite manifest, imported chunk, and dev-server tag generation
  • default render options
  • Echo v5 adapter

Integration Notes

  • Register Renderer.Middleware or the framework adapter middleware before routes that render Inertia pages.
  • Values in Props, shared props, flash data, and validation errors are sent to the browser. Do not put secrets in them.
  • For larger pages, define page-specific Go structs and convert them to inertia.Props at the render boundary. This keeps the server/frontend contract easier to review.
  • NewMemoryFlashStore is intended for local development, tests, and single-process examples. Production and clustered applications should implement FlashStore with their session store, Redis, a database, or another shared backend.
  • go build builds Go code only. Templates and Vite assets are deployed as files unless your application embeds them.

Core Example

package main

import (
	"net/http"

	inertia "github.com/mayahiro/go-inertia"
)

func main() {
	rootView, err := inertia.NewTemplateRootViewFromFile("views/app.html", "app.html")
	if err != nil {
		panic(err)
	}

	renderer, err := inertia.New(inertia.Config{
		RootView: rootView,
		SharedProps: inertia.StaticSharedProps(inertia.Props{
			"app": map[string]any{"name": "Admin"},
		}),
	})
	if err != nil {
		panic(err)
	}

	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		err := renderer.Render(w, req, "Dashboard", inertia.Props{
			"message": "Hello",
		})
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})

	http.ListenAndServe(":8080", renderer.Middleware(mux))
}

Root Template

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    {{ .ViteTags }}
    {{ .InertiaHead }}
  </head>
  <body>
    {{ .InertiaScript }}
    <div id="app"></div>
  </body>
</html>

Echo Example

package main

import (
	"net/http"

	echo "github.com/labstack/echo/v5"
	inertia "github.com/mayahiro/go-inertia"
	inertiaecho "github.com/mayahiro/go-inertia/adapters/echo"
)

func main() {
	rootView, err := inertia.NewTemplateRootViewFromFile("views/app.html", "app.html")
	if err != nil {
		panic(err)
	}

	renderer, err := inertia.New(inertia.Config{
		RootView:   rootView,
		FlashStore: inertia.NewMemoryFlashStore(),
	})
	if err != nil {
		panic(err)
	}

	app := inertiaecho.New(renderer)
	e := echo.New()
	e.Use(app.Middleware)

	e.GET("/", func(c *echo.Context) error {
		return app.Render(c, "Dashboard", inertia.Props{
			"message": "Hello",
		})
	})

	e.POST("/users", func(c *echo.Context) error {
		return app.Redirect(c, "/users", inertia.WithFlash(inertia.Flash{
			"success": "User created",
		}))
	})

	if err := e.Start(":8080"); err != nil && err != http.ErrServerClosed {
		e.Logger.Error("server error", "error", err)
	}
}

Vite

Use NewVite to generate tags for a Vite entrypoint.

Development mode:

vite, err := inertia.NewVite(inertia.ViteConfig{
	DevServerURL: "http://127.0.0.1:5173",
	Entry:        "resources/js/app.tsx",
	ReactRefresh: true,
})

Production mode:

vite, err := inertia.NewVite(inertia.ViteConfig{
	ManifestPath: "public/build/.vite/manifest.json",
	PublicPath:   "/build",
	Entry:        "resources/js/app.tsx",
})

Set generated tags as default render options when every page uses the same root template assets.

tags, err := vite.Tags()
if err != nil {
	return err
}

renderer, err := inertia.New(inertia.Config{
	RootView:        rootView,
	VersionProvider: vite.VersionProvider(),
	DefaultRenderOptions: []inertia.RenderOption{
		inertia.WithViteTags(tags),
	},
})

You can still pass inertia.WithViteTags(tags) to an individual Render call when a request needs to override the default tags.

Flash and Validation

Inertia validation usually redirects back and flashes validation errors instead of returning 422 JSON responses. go-inertia provides the FlashStore interface and a small in-memory implementation for development use.

renderer, err := inertia.New(inertia.Config{
	RootView:   rootView,
	FlashStore: inertia.NewMemoryFlashStore(),
})

Use Back and WithValidationErrors after validation fails.

return renderer.Back(w, req, inertia.WithValidationErrors(inertia.ValidationErrors{
	"name": "Name is required",
}))

Inertia preserves component state after non-GET requests, so applications usually do not need to send old input back through server props.

Lazy, Optional, and Always Props

Plain func(*http.Request) (any, error) props are evaluated lazily. During a matching partial reload, the callback only runs when the prop is included by only or not excluded by except.

"companies": func(req *http.Request) (any, error) {
	return loadCompanies(req.Context())
}

Use Optional for props that should only be sent when explicitly requested with the client only option.

"companies": inertia.Optional(loadCompanies)

Use Always for props that should be sent even during partial reloads.

"auth": inertia.Always(currentUser)

Deferred Props

Use Defer for props that should be loaded after the first page render. The callback runs only when the Inertia client requests the prop through a partial reload.

err := renderer.Render(w, req, "Users/Index", inertia.Props{
	"users": UserList(),
	"permissions": inertia.Defer(func(req *http.Request) (any, error) {
		return PermissionList(req.Context())
	}),
})

Deferred props are grouped under default. Pass a group name when several props should load in a separate request group.

"teams": inertia.Defer(loadTeams, "attributes")

Once Props

Use Once for props that the client can reuse after the first response.

err := renderer.Render(w, req, "Dashboard", inertia.Props{
	"plans": inertia.Once(func(req *http.Request) (any, error) {
		return BillingPlans(req.Context())
	}),
})

Use As to share a once key across prop names, Fresh to force a reload, and Until to send an expiration timestamp.

"availableRoles": inertia.Once(loadRoles).As("roles")

Merge Props

Use Merge for props that should append during partial reloads.

err := renderer.Render(w, req, "Items/Index", inertia.Props{
	"items": inertia.Merge(items),
})

Target nested paths with Append and Prepend, and use MatchOn when items should be matched by an identifier instead of appended blindly.

"results": inertia.Merge(results).Append("data").MatchOn("data.id")

Use DeepMerge when the whole prop should be deeply merged.

"chat": inertia.Merge(chat).DeepMerge().MatchOn("messages.id")

Composable Prop Modifiers

Defer, Merge, Once, Optional, Always, and lazy props share the same modifier model. Combine them when the Inertia protocol supports the result.

"results": inertia.Defer(loadResults).DeepMerge().MatchOn("data.id")
"permissions": inertia.Defer(loadPermissions).Once()
"activity": inertia.Merge(loadActivity).Once()
"companies": inertia.Optional(loadCompanies).Once()

Infinite Scroll

Use Scroll for paginated props rendered with the Inertia client InfiniteScroll component. go-inertia does not normalize paginator structs; pass the prop value and pagination metadata explicitly.

err := renderer.Render(w, req, "Posts/Index", inertia.Props{
	"posts": inertia.Scroll(inertia.Props{
		"data": posts,
	}, inertia.ScrollMetadata{
		PreviousPage: nil,
		NextPage:     2,
		CurrentPage:  1,
	}),
})

Scroll merges the data wrapper by default and sets scrollProps metadata. Use Wrapper for a different item wrapper and MatchOn when items should be matched by an identifier.

"feed": inertia.Scroll(feed, metadata).Wrapper("items").MatchOn("items.id")

Scroll follows the Inertia protocol and does not reset loaded scroll data by itself after form submissions. Use the client reset visit option when a successful mutation should reload a scroll prop from the first page. Omit reset when the current loaded list should stay in place.

Precognition

Precognition requests are validation-only requests. Use IsPrecognition and PrecognitionValidateOnly to detect them and limit validation work.

if inertia.IsPrecognition(req) {
	if len(errors) > 0 {
		return inertia.PrecognitionErrors(w, errors)
	}
	inertia.PrecognitionSuccess(w)
	return nil
}

Precognition helpers are separate from normal Inertia validation. Regular form submissions should still redirect and flash validation errors.

History Flags

Use render options to set Inertia history flags on a page response.

return renderer.Render(w, req, "Account/Security", props,
	inertia.WithEncryptHistory(),
	inertia.WithClearHistory(),
)

React + Vite Example

See examples/echo-react-vite for a TypeScript React + Vite + Echo example.

Documentation

Not Yet Covered by Public Helpers

Some Inertia workflows are not covered by public helpers yet.

  • server-side rendering
  • deferred prop rescue metadata (rescuedProps)
  • instant-visit shared prop metadata (sharedProps)
  • production-ready session store
  • Echo v4 adapter
  • adapters for frameworks other than Echo v5
  • CLI scaffolding

Development

Go imports and formatting are handled by goimports. The tool dependency is kept in a separate tools module so the public root module stays dependency free.

cd tools
go tool goimports -w ..

Run the core checks:

go test ./...
go vet ./...

Run the Echo adapter checks:

cd adapters/echo
go test ./...
go vet ./...

Run the example checks:

cd examples/echo-react-vite
npm ci
npm run build
go test ./...
go vet ./...

References

License

MIT

Documentation

Overview

Package inertia implements the server-side parts of the Inertia protocol.

The package is built on net/http and has no runtime dependencies outside the Go standard library. Use New to create a Renderer, register Renderer.Middleware in your HTTP stack, and call Renderer.Render from handlers to return Inertia pages.

Framework adapters wrap Renderer instead of reimplementing protocol behavior. Flash data and validation errors are exposed through FlashStore; the package does not include a production session store.

Index

Constants

View Source
const (
	// HeaderInertia is the request and response header that marks an Inertia request or response.
	HeaderInertia = "X-Inertia"
	// HeaderInertiaVersion carries the client asset version.
	HeaderInertiaVersion = "X-Inertia-Version"
	// HeaderInertiaLocation carries the target URL for an Inertia location visit.
	HeaderInertiaLocation = "X-Inertia-Location"
	// HeaderInertiaRedirect carries a redirect target that should preserve the URL fragment.
	HeaderInertiaRedirect = "X-Inertia-Redirect"
	// HeaderInertiaPartialComponent carries the component name for a partial reload.
	HeaderInertiaPartialComponent = "X-Inertia-Partial-Component"
	// HeaderInertiaPartialData carries the prop names to include in a partial reload.
	HeaderInertiaPartialData = "X-Inertia-Partial-Data"
	// HeaderInertiaPartialExcept carries the prop names to exclude in a partial reload.
	HeaderInertiaPartialExcept = "X-Inertia-Partial-Except"
	// HeaderInertiaReset carries the prop names to reset before merging.
	HeaderInertiaReset = "X-Inertia-Reset"
	// HeaderInertiaErrorBag carries the requested validation error bag name.
	HeaderInertiaErrorBag = "X-Inertia-Error-Bag"
	// HeaderInertiaInfiniteScrollMergeIntent carries append or prepend intent for infinite scroll.
	HeaderInertiaInfiniteScrollMergeIntent = "X-Inertia-Infinite-Scroll-Merge-Intent"
	// HeaderInertiaExceptOnceProps carries once prop keys already loaded by the client.
	HeaderInertiaExceptOnceProps = "X-Inertia-Except-Once-Props"
	// HeaderPurpose carries request purpose hints such as prefetch.
	HeaderPurpose = "Purpose"
	// HeaderPrecognition marks Precognition validation requests and responses.
	HeaderPrecognition = "Precognition"
	// HeaderPrecognitionValidateOnly carries field names to validate during Precognition.
	HeaderPrecognitionValidateOnly = "Precognition-Validate-Only"
	// HeaderPrecognitionSuccess marks successful Precognition validation responses.
	HeaderPrecognitionSuccess = "Precognition-Success"
)

Variables

View Source
var (
	// ErrMissingRootView is returned when Config.RootView is not set.
	ErrMissingRootView = errors.New("inertia: missing root view")
	// ErrMissingFlashStore is returned when flash data is used without a FlashStore.
	ErrMissingFlashStore = errors.New("inertia: flash store is not configured")
	// ErrInvalidComponent is returned when a render call receives an empty component name.
	ErrInvalidComponent = errors.New("inertia: component must not be empty")
	// ErrComponentNotFound is returned when a configured component checker cannot find a component.
	ErrComponentNotFound = errors.New("inertia: component not found")
	// ErrInvalidScrollPaginator is returned when ScrollPage receives a nil paginator.
	ErrInvalidScrollPaginator = errors.New("inertia: scroll paginator is nil")
)

Functions

func AppendVary

func AppendVary(h http.Header, value string)

AppendVary appends value to the Vary header without duplicating existing values.

func ErrorBag

func ErrorBag(req *http.Request) string

ErrorBag returns the requested validation error bag name from req.

func ExceptOnceProps added in v0.2.0

func ExceptOnceProps(req *http.Request) []string

ExceptOnceProps returns once prop keys the client has already loaded.

func InfiniteScrollMergeIntent added in v0.2.0

func InfiniteScrollMergeIntent(req *http.Request) string

InfiniteScrollMergeIntent returns the requested infinite scroll merge intent.

func IsInertiaRequest

func IsInertiaRequest(req *http.Request) bool

IsInertiaRequest reports whether req is an Inertia request.

func IsPartialReload

func IsPartialReload(req *http.Request) bool

IsPartialReload reports whether req asks for a partial reload.

func IsPrecognition added in v0.2.0

func IsPrecognition(req *http.Request) bool

IsPrecognition reports whether req is a Precognition validation request.

func IsPrefetch added in v0.2.0

func IsPrefetch(req *http.Request) bool

IsPrefetch reports whether req is an Inertia prefetch request.

func PartialComponent

func PartialComponent(req *http.Request) string

PartialComponent returns the partial reload component name from req.

func PartialData

func PartialData(req *http.Request) []string

PartialData returns the requested partial reload prop names from req.

func PartialExcept

func PartialExcept(req *http.Request) []string

PartialExcept returns the excluded partial reload prop names from req.

func PrecognitionErrors added in v0.2.0

func PrecognitionErrors(w http.ResponseWriter, errors ValidationErrors) error

PrecognitionErrors writes a failed Precognition validation response.

func PrecognitionSuccess added in v0.2.0

func PrecognitionSuccess(w http.ResponseWriter)

PrecognitionSuccess writes a successful Precognition validation response.

func PrecognitionValidateOnly added in v0.2.0

func PrecognitionValidateOnly(req *http.Request) []string

PrecognitionValidateOnly returns field names requested for Precognition validation.

func ResetProps added in v0.2.0

func ResetProps(req *http.Request) []string

ResetProps returns prop names the client wants to reset before merging.

func WithFlashContext

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

WithFlashContext stores flash data in ctx for the current request.

func WithProps

func WithProps(ctx context.Context, props Props) context.Context

WithProps stores request-scoped props in ctx.

func WithSharedProps

func WithSharedProps(ctx context.Context, props Props) context.Context

WithSharedProps stores request-scoped shared props in ctx.

func WithValidationErrorsContext

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

WithValidationErrorsContext stores validation errors in ctx for the current request.

Types

type ComponentExistenceChecker added in v0.3.0

type ComponentExistenceChecker interface {
	// ComponentExists reports whether component exists.
	ComponentExists(component string) (bool, error)
}

ComponentExistenceChecker checks whether a component exists.

type ComponentExistsFunc added in v0.3.0

type ComponentExistsFunc func(component string) (bool, error)

ComponentExistsFunc adapts a function to ComponentExistenceChecker.

func (ComponentExistsFunc) ComponentExists added in v0.3.0

func (f ComponentExistsFunc) ComponentExists(component string) (bool, error)

ComponentExists calls f(component).

type ComponentNameTransformer added in v0.3.0

type ComponentNameTransformer func(component string) string

ComponentNameTransformer transforms component names before rendering.

type ComponentNotFoundError added in v0.3.0

type ComponentNotFoundError struct {
	// Component is the transformed component name that was checked.
	Component string
}

ComponentNotFoundError is returned when a configured checker cannot find a component.

func (ComponentNotFoundError) Error added in v0.3.0

func (e ComponentNotFoundError) Error() string

Error returns the error message.

func (ComponentNotFoundError) Is added in v0.3.0

func (e ComponentNotFoundError) Is(target error) bool

Is reports whether target is ErrComponentNotFound.

type Config

type Config struct {
	// RootView renders the initial HTML document.
	RootView RootView
	// VersionProvider returns the current asset version.
	VersionProvider VersionProvider
	// SharedProps returns props that are merged into every page.
	SharedProps SharedPropsProvider
	// FlashStore stores one-time flash data and validation errors across redirects.
	FlashStore FlashStore
	// URLResolver returns the URL written into the Inertia page object.
	URLResolver URLResolver
	// JSONEncoder encodes Inertia page objects.
	JSONEncoder JSONEncoder
	// DefaultRenderOptions are applied to every Render call before request options.
	DefaultRenderOptions []RenderOption
	// ComponentNameTransformer transforms component names before rendering.
	ComponentNameTransformer ComponentNameTransformer
	// ComponentExistenceChecker checks transformed component names before rendering.
	ComponentExistenceChecker ComponentExistenceChecker
}

Config configures a Renderer.

type DeferredFunc added in v0.2.0

type DeferredFunc = PropFunc

DeferredFunc loads a deferred prop for req.

type DeferredProp added in v0.2.0

type DeferredProp = Prop

DeferredProp marks a page prop as deferred until a matching partial reload.

func Defer added in v0.2.0

func Defer(fn DeferredFunc, group ...string) DeferredProp

Defer returns a prop that is omitted from the initial page response.

type Flash

type Flash Props

Flash is the set of one-time props sent after a redirect.

func FlashFromContext

func FlashFromContext(ctx context.Context) Flash

FlashFromContext returns flash data stored in ctx.

type FlashData

type FlashData struct {
	// Flash contains one-time flash props.
	Flash Flash
	// Errors contains default validation errors.
	Errors ValidationErrors
	// Bags contains named validation error bags.
	Bags map[string]ValidationErrors
}

FlashData is the data stored by a FlashStore.

type FlashStore

type FlashStore interface {
	// Pull reads and clears flash data for req.
	Pull(req *http.Request) (FlashData, error)
	// Put stores flash data for the next request.
	Put(w http.ResponseWriter, req *http.Request, data FlashData) error
	// Reflash preserves existing flash data for another request.
	Reflash(w http.ResponseWriter, req *http.Request) error
}

FlashStore stores one-time flash data and validation errors across redirects.

type JSONEncoder

type JSONEncoder interface {
	// Encode returns the JSON representation of v.
	Encode(v any) ([]byte, error)
}

JSONEncoder encodes values for Inertia JSON responses.

type MemoryFlashStore added in v0.1.1

type MemoryFlashStore struct {
	CookieName     string
	CookiePath     string
	CookieSecure   bool
	CookieSameSite http.SameSite
	// contains filtered or unexported fields
}

func NewMemoryFlashStore added in v0.1.1

func NewMemoryFlashStore() *MemoryFlashStore

func (*MemoryFlashStore) Pull added in v0.1.1

func (s *MemoryFlashStore) Pull(req *http.Request) (FlashData, error)

func (*MemoryFlashStore) Put added in v0.1.1

func (*MemoryFlashStore) Reflash added in v0.1.1

func (s *MemoryFlashStore) Reflash(w http.ResponseWriter, req *http.Request) error

type MergeFunc added in v0.2.0

type MergeFunc = PropFunc

MergeFunc loads a mergeable prop for req.

type MergeProp added in v0.2.0

type MergeProp = Prop

MergeProp marks a page prop as mergeable during partial reloads.

func Merge added in v0.2.0

func Merge(value any) MergeProp

Merge returns a prop that appends at the root path by default.

type NoopFlashStore

type NoopFlashStore struct{}

NoopFlashStore is a FlashStore implementation that stores no data.

func (NoopFlashStore) Pull

func (NoopFlashStore) Pull(req *http.Request) (FlashData, error)

Pull returns no flash data.

func (NoopFlashStore) Put

Put ignores data.

func (NoopFlashStore) Reflash

Reflash does nothing.

type OnceFunc added in v0.2.0

type OnceFunc = PropFunc

OnceFunc loads a prop that the Inertia client remembers across visits.

type OnceProp added in v0.2.0

type OnceProp = Prop

OnceProp marks a page prop as reusable after the client receives it once.

func Once added in v0.2.0

func Once(fn OnceFunc) OnceProp

Once returns a prop that is resolved once and then reused by the client.

type OncePropMetadata added in v0.2.0

type OncePropMetadata struct {
	// Prop is the page prop path reused by the client.
	Prop string `json:"prop"`
	// ExpiresAt is a Unix millisecond timestamp, or nil when the prop does not expire.
	ExpiresAt *int64 `json:"expiresAt"`
}

OncePropMetadata describes an Inertia once prop entry in the page object.

type Page

type Page struct {
	// Component is the client-side component name.
	Component string `json:"component"`
	// Props contains the data for the client-side component.
	Props Props `json:"props"`
	// URL is the current request URL as seen by Inertia.
	URL string `json:"url"`
	// Version is the current asset version.
	Version any `json:"version,omitempty"`
	// EncryptHistory requests encrypted browser history state when supported by the client.
	EncryptHistory bool `json:"encryptHistory,omitempty"`
	// ClearHistory requests clearing browser history state when supported by the client.
	ClearHistory bool `json:"clearHistory,omitempty"`
	// PreserveFragment requests preserving the current URL fragment when supported by the client.
	PreserveFragment bool `json:"preserveFragment,omitempty"`
	// RescuedProps lists deferred props that failed and were rescued.
	RescuedProps []string `json:"rescuedProps,omitempty"`
	// SharedProps lists shared prop names when supported by the client.
	SharedProps []string `json:"sharedProps,omitempty"`
	// MergeProps lists prop paths that should be appended during navigation.
	MergeProps []string `json:"mergeProps,omitempty"`
	// PrependProps lists prop paths that should be prepended during navigation.
	PrependProps []string `json:"prependProps,omitempty"`
	// DeepMergeProps lists prop paths that should be deeply merged during navigation.
	DeepMergeProps []string `json:"deepMergeProps,omitempty"`
	// MatchPropsOn lists prop paths used to match items while merging arrays.
	MatchPropsOn []string `json:"matchPropsOn,omitempty"`
	// ScrollProps contains infinite scroll metadata keyed by prop name.
	ScrollProps map[string]ScrollMetadata `json:"scrollProps,omitempty"`
	// DeferredProps groups deferred prop names by request group.
	DeferredProps map[string][]string `json:"deferredProps,omitempty"`
	// OnceProps contains once prop metadata keyed by once prop key.
	OnceProps map[string]OncePropMetadata `json:"onceProps,omitempty"`
}

Page is the Inertia page object sent to the browser.

type Prop added in v0.2.0

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

Prop is a page prop with optional Inertia protocol modifiers.

func Always added in v0.2.0

func Always(value any) Prop

Always returns a prop that is included even during partial reloads.

func Lazy added in v0.2.0

func Lazy(fn PropFunc) Prop

Lazy returns a prop that is evaluated only when the response includes it.

func Optional added in v0.2.0

func Optional(value any) Prop

Optional returns a prop that is only included when explicitly requested.

func (Prop) Always added in v0.2.0

func (p Prop) Always() Prop

Always returns p configured to be included even during partial reloads.

func (Prop) Append added in v0.2.0

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

Append returns p configured to append the given relative prop paths.

func (Prop) As added in v0.2.0

func (p Prop) As(key string) Prop

As returns p with a custom once key shared across matching once props.

func (Prop) DeepMerge added in v0.2.0

func (p Prop) DeepMerge() Prop

DeepMerge returns p configured to deeply merge the whole prop.

func (Prop) Defer added in v0.2.0

func (p Prop) Defer(group ...string) Prop

Defer returns p configured as a deferred prop.

func (Prop) Fresh added in v0.2.0

func (p Prop) Fresh(fresh ...bool) Prop

Fresh returns p configured to ignore the client's remembered once value.

func (Prop) MatchOn added in v0.2.0

func (p Prop) MatchOn(paths ...string) Prop

MatchOn returns p configured to match merged items by the given relative paths.

func (Prop) Merge added in v0.2.0

func (p Prop) Merge() Prop

Merge returns p configured to append at the root path.

func (Prop) Once added in v0.2.0

func (p Prop) Once() Prop

Once returns p configured to be reused by the client after it is loaded.

func (Prop) Optional added in v0.2.0

func (p Prop) Optional() Prop

Optional returns p configured to be included only when explicitly requested.

func (Prop) Prepend added in v0.2.0

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

Prepend returns p configured to prepend the given relative prop paths.

func (Prop) Rescue added in v0.3.0

func (p Prop) Rescue(rescue ...bool) Prop

Rescue omits a failed deferred prop and marks it in Page.RescuedProps.

func (Prop) Scroll added in v0.3.0

func (p Prop) Scroll(metadata ScrollMetadata) Prop

Scroll returns p configured as an infinite scroll prop.

func (Prop) Until added in v0.2.0

func (p Prop) Until(t time.Time) Prop

Until returns p with an expiration timestamp sent to the client.

func (Prop) Wrapper added in v0.2.0

func (p Prop) Wrapper(path string) Prop

Wrapper returns p configured to merge a custom infinite scroll data wrapper.

type PropFunc added in v0.2.0

type PropFunc func(req *http.Request) (any, error)

PropFunc loads a prop for req.

type Props

type Props map[string]any

Props is the set of top-level props sent to the Inertia page component.

func PropsFromContext

func PropsFromContext(ctx context.Context) Props

PropsFromContext returns request-scoped props from ctx.

func SharedPropsFromContext

func SharedPropsFromContext(ctx context.Context) Props

SharedPropsFromContext returns request-scoped shared props from ctx.

type RedirectOption

type RedirectOption func(*redirectOptions)

RedirectOption configures a redirect response.

func WithErrorBag

func WithErrorBag(name string) RedirectOption

WithErrorBag stores validation errors in the named error bag.

func WithFlash

func WithFlash(data Flash) RedirectOption

WithFlash stores flash data for the next request.

func WithPreserveFragment

func WithPreserveFragment() RedirectOption

WithPreserveFragment requests an Inertia redirect that preserves the URL fragment.

func WithStatus

func WithStatus(code int) RedirectOption

WithStatus overrides the HTTP redirect status.

func WithValidationErrors

func WithValidationErrors(errors ValidationErrors) RedirectOption

WithValidationErrors stores validation errors for the next request.

type RenderOption

type RenderOption func(*renderOptions)

RenderOption configures a single Render call.

func WithClearHistory added in v0.2.0

func WithClearHistory(clear ...bool) RenderOption

WithClearHistory sets Page.ClearHistory for the rendered page.

func WithEncryptHistory added in v0.2.0

func WithEncryptHistory(encrypt ...bool) RenderOption

WithEncryptHistory sets Page.EncryptHistory for the rendered page.

func WithInertiaHead

func WithInertiaHead(head template.HTML) RenderOption

WithInertiaHead sets HTML that should be rendered in the Inertia head placeholder.

func WithRenderPreserveFragment

func WithRenderPreserveFragment() RenderOption

WithRenderPreserveFragment sets Page.PreserveFragment for the rendered page.

func WithRenderStatus added in v0.3.0

func WithRenderStatus(code int) RenderOption

WithRenderStatus sets the HTTP status code for a rendered page.

func WithViewData

func WithViewData(data map[string]any) RenderOption

WithViewData adds extra data for the RootView template.

func WithViteTags

func WithViteTags(tags template.HTML) RenderOption

WithViteTags sets HTML tags generated by Vite.

type Renderer

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

Renderer renders Inertia pages, handles protocol middleware, and creates Inertia redirects.

func New

func New(config Config) (*Renderer, error)

New creates a Renderer from config.

func (*Renderer) Back

func (r *Renderer) Back(w http.ResponseWriter, req *http.Request, opts ...RedirectOption) error

Back redirects to the Referer header or to "/" when no Referer is present.

func (*Renderer) Location

func (r *Renderer) Location(w http.ResponseWriter, req *http.Request, url string) error

Location sends an Inertia location response or a normal redirect for non-Inertia requests.

func (*Renderer) Middleware

func (r *Renderer) Middleware(next http.Handler) http.Handler

Middleware returns an HTTP middleware that handles Inertia protocol concerns.

func (*Renderer) Redirect

func (r *Renderer) Redirect(w http.ResponseWriter, req *http.Request, url string, opts ...RedirectOption) error

Redirect sends a redirect response and stores flash data when configured.

func (*Renderer) Render

func (r *Renderer) Render(w http.ResponseWriter, req *http.Request, component string, props Props, opts ...RenderOption) error

Render renders an Inertia page.

For Inertia requests it writes a JSON page response. For normal browser visits it renders the configured RootView.

func (*Renderer) RenderError added in v0.3.0

func (r *Renderer) RenderError(w http.ResponseWriter, req *http.Request, component string, props Props, status int, opts ...RenderOption) error

RenderError renders an Inertia error page with status.

type RootView

type RootView interface {
	// Render writes the root document using data.
	Render(w io.Writer, data RootViewData) error
}

RootView renders the root HTML document for initial browser visits.

func NewTemplateRootView

func NewTemplateRootView(t *template.Template, name string) RootView

NewTemplateRootView creates a RootView from t and template name.

func NewTemplateRootViewFromFS

func NewTemplateRootViewFromFS(fsys fs.FS, path string, name string) (RootView, error)

NewTemplateRootViewFromFS parses path from fsys and returns a RootView.

func NewTemplateRootViewFromFile

func NewTemplateRootViewFromFile(path string, name string) (RootView, error)

NewTemplateRootViewFromFile parses path and returns a RootView.

type RootViewData

type RootViewData struct {
	// Page is the Inertia page object.
	Page Page
	// PageJSON is the safe JSON representation of Page.
	PageJSON template.JS
	// InertiaScript is the script tag containing PageJSON.
	InertiaScript template.HTML
	// InertiaHead is HTML rendered in the document head.
	InertiaHead template.HTML
	// ViteTags contains script and stylesheet tags for Vite assets.
	ViteTags template.HTML
	// Data contains additional template data.
	Data map[string]any
}

RootViewData contains the data passed to a RootView.

type ScrollFunc added in v0.2.0

type ScrollFunc = PropFunc

ScrollFunc loads an infinite scroll prop for req.

type ScrollMetadata added in v0.2.0

type ScrollMetadata struct {
	// PageName is the query parameter used for this scroll container.
	PageName string `json:"pageName"`
	// PreviousPage is the previous page value, or nil when there is no previous page.
	PreviousPage any `json:"previousPage"`
	// NextPage is the next page value, or nil when there is no next page.
	NextPage any `json:"nextPage"`
	// CurrentPage is the current page value.
	CurrentPage any `json:"currentPage"`
	// Reset marks the scroll prop as reset for the current response.
	Reset bool `json:"reset,omitempty"`
}

ScrollMetadata describes pagination state for an infinite scroll prop.

type ScrollPaginator added in v0.3.0

type ScrollPaginator interface {
	// ScrollItems returns the items for the current page.
	ScrollItems() any
	// ScrollMetadata returns the pagination state for the current page.
	ScrollMetadata() ScrollMetadata
}

ScrollPaginator exposes paginated data in the shape required by ScrollPage.

type ScrollProp added in v0.2.0

type ScrollProp = Prop

ScrollProp marks a page prop as an infinite scroll prop.

func Scroll added in v0.2.0

func Scroll(value any, metadata ScrollMetadata) ScrollProp

Scroll returns an infinite scroll prop with explicit pagination metadata.

func ScrollPage added in v0.3.0

func ScrollPage(paginator ScrollPaginator, wrapper ...string) ScrollProp

ScrollPage returns an infinite scroll prop from a paginator interface.

type SharedPropsFunc

type SharedPropsFunc func(req *http.Request) (Props, error)

SharedPropsFunc adapts a function to SharedPropsProvider.

func (SharedPropsFunc) Props

func (f SharedPropsFunc) Props(req *http.Request) (Props, error)

Props calls f(req).

type SharedPropsProvider

type SharedPropsProvider interface {
	// Props returns shared props for req.
	Props(req *http.Request) (Props, error)
}

SharedPropsProvider returns props that are shared by every Inertia page.

func NoSharedProps

func NoSharedProps() SharedPropsProvider

NoSharedProps returns a provider that returns no shared props.

func StaticSharedProps

func StaticSharedProps(props Props) SharedPropsProvider

StaticSharedProps returns a provider that always returns props.

type StandardJSONEncoder

type StandardJSONEncoder struct{}

StandardJSONEncoder encodes values with encoding/json.

func (StandardJSONEncoder) Encode

func (StandardJSONEncoder) Encode(v any) ([]byte, error)

Encode returns the JSON representation of v.

type TemplateRootView

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

TemplateRootView renders a RootView with html/template.

func (*TemplateRootView) Render

func (v *TemplateRootView) Render(w io.Writer, data RootViewData) error

Render executes the configured template.

type URLResolver

type URLResolver interface {
	// URL returns the URL for req.
	URL(req *http.Request) string
}

URLResolver returns the URL stored in the Inertia page object.

type URLResolverFunc

type URLResolverFunc func(req *http.Request) string

URLResolverFunc adapts a function to URLResolver.

func (URLResolverFunc) URL

func (f URLResolverFunc) URL(req *http.Request) string

URL calls f(req).

type ValidationErrors

type ValidationErrors map[string]any

ValidationErrors is a map of validation error values keyed by field or bag name.

func ValidationErrorsFromContext

func ValidationErrorsFromContext(ctx context.Context) ValidationErrors

ValidationErrorsFromContext returns validation errors stored in ctx.

type VersionProvider

type VersionProvider interface {
	// Version returns the current asset version.
	Version(ctx context.Context) (any, error)
}

VersionProvider returns the current Inertia asset version.

func StaticVersion

func StaticVersion(version any) VersionProvider

StaticVersion returns a provider that always returns version.

func VersionFromFSFileHash

func VersionFromFSFileHash(fsys fs.FS, path string) VersionProvider

VersionFromFSFileHash returns a provider that hashes a file from fsys.

func VersionFromFileHash

func VersionFromFileHash(path string) VersionProvider

VersionFromFileHash returns a provider that hashes the file at path.

type VersionProviderFunc

type VersionProviderFunc func(ctx context.Context) (any, error)

VersionProviderFunc adapts a function to VersionProvider.

func (VersionProviderFunc) Version

func (f VersionProviderFunc) Version(ctx context.Context) (any, error)

Version calls f(ctx).

type Vite

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

Vite generates script and stylesheet tags for Vite assets.

func NewVite

func NewVite(config ViteConfig) (*Vite, error)

NewVite creates a Vite helper from config.

func (*Vite) Tags

func (v *Vite) Tags() (template.HTML, error)

Tags returns HTML tags for the configured Vite entry.

func (*Vite) Version

func (v *Vite) Version(ctx context.Context) (any, error)

Version returns the current Vite asset version.

func (*Vite) VersionProvider

func (v *Vite) VersionProvider() VersionProvider

VersionProvider returns a VersionProvider based on the Vite configuration.

type ViteConfig

type ViteConfig struct {
	// ManifestPath is the path to Vite's manifest file.
	ManifestPath string
	// ManifestFS is the optional filesystem used to read ManifestPath.
	ManifestFS fs.FS
	// PublicPath is the public URL prefix for built assets.
	PublicPath string
	// Entry is the Vite entrypoint key in the manifest.
	Entry string
	// DevServerURL enables development mode when set.
	DevServerURL string
	// ReactRefresh enables the React refresh preamble in development mode.
	ReactRefresh bool
}

ViteConfig configures Vite asset tag generation.

Directories

Path Synopsis
adapters
echo module

Jump to

Keyboard shortcuts

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