### Install frontend dependencies Source: https://github.com/assurrussa/goinertia/blob/master/examples/basic-app-react/README.md Run this command from the examples/basic-app-react directory to install the frontend dependencies. ```bash cd examples/basic-app-react npm install ``` -------------------------------- ### Native net/http adapter setup and handler Source: https://github.com/assurrussa/goinertia/blob/master/docs/adapters.md Initializes the net/http adapter with validation and core options, creates a handler that sets a prop and renders a view, and wraps the mux with middleware. The middleware installs a concrete core.State; props and view data are request-scoped. State is not safe for concurrent mutation or reuse across requests. ```go import ( "net/http" "github.com/assurrussa/goinertia/core" "github.com/assurrussa/goinertia/adapters/nethttp" "github.com/assurrussa/goinertia/views" ) manager, err := nethttp.NewWithValidation("https://app.example", nethttp.WithCoreOptions(core.WithFS(views.Templates), core.WithAssetVersion("v1")), ) if err != nil { panic(err) } mux := http.NewServeMux() mux.Handle("/", manager.Handler(func(w http.ResponseWriter, r *http.Request) error { manager.WithProp(nethttp.State(r), "message", "Hello") return manager.Render(w, r, "Home", nil) })) handler := manager.Middleware(mux) ``` -------------------------------- ### Install frontend dependencies Source: https://github.com/assurrussa/goinertia/blob/master/examples/basic-app-react-ssr/README.md Run this command in the examples/basic-app-react-ssr directory to install the frontend dependencies. ```bash cd examples/basic-app-react-ssr npm install ``` -------------------------------- ### Run basic example (make run-example-base) Source: https://github.com/assurrussa/goinertia/blob/master/CONTRIBUTING.md Runs the basic example. Optionally specify a custom port with PORT=8383. ```bash make run-example-base ``` ```bash make run-example-base PORT=8383 ``` -------------------------------- ### Install frontend dependencies Source: https://github.com/assurrussa/goinertia/blob/master/examples/basic-app/README.md Run this command in the examples/basic-app directory to install the required npm packages for the Vue client. ```bash cd examples/basic-app npm install ``` -------------------------------- ### Setup and run full matrix Source: https://github.com/assurrussa/goinertia/blob/master/integration/browser/README.md Commands to install dependencies and run the complete browser test matrix. Requires Go 1.26, Node 24, npm, and Playwright Chromium. The matrix runs sequentially, stops at first failure, and disables retries. Ports 18985 and 19000-19003 must be free. ```sh cd integration/browser npm ci npm ci --prefix v3 npx playwright install --with-deps chromium npm run matrix ``` -------------------------------- ### Start SSR renderer for Vue or React Source: https://github.com/assurrussa/goinertia/blob/master/examples/v3-app/README.md Run the SSR renderer in the example directory. It binds only to loopback and listens on port 13714 by default. ```sh npm run ssr ``` -------------------------------- ### Run the v3-app example Source: https://github.com/assurrussa/goinertia/blob/master/README.md Builds and runs the runnable v3-app example from a checkout. Requires Go 1.26+ and Node 24. Use FRAMEWORK=react for React and -adapter nethttp for native net/http. ```sh cd examples/v3-app npm ci FRAMEWORK=vue npm run build # Or: FRAMEWORK=react npm run build cd ../.. go run ./examples/v3-app -adapter fiber # Or: go run ./examples/v3-app -adapter nethttp ``` -------------------------------- ### Install goinertia with go get Source: https://github.com/assurrussa/goinertia/blob/master/README.md Adds the goinertia module to your Go project. Run this command in your project directory. ```bash go get github.com/assurrussa/goinertia ``` -------------------------------- ### Install dependencies and build frontend for Vue or React Source: https://github.com/assurrussa/goinertia/blob/master/examples/v3-app/README.md Run npm ci to install dependencies, then build the frontend with FRAMEWORK=vue or FRAMEWORK=react. The build output is used by the Go server. ```sh npm ci FRAMEWORK=vue npm run build # Or: FRAMEWORK=react npm run build ``` -------------------------------- ### Start the SSR server Source: https://github.com/assurrussa/goinertia/blob/master/examples/basic-app-react-ssr/README.md Run this command to start the SSR server. ```bash npm run serve:ssr ``` -------------------------------- ### Run the Go server from repo root Source: https://github.com/assurrussa/goinertia/blob/master/examples/basic-app-react-ssr/README.md Run this command from the repo root to start the Go server. Then open http://localhost:8383. ```bash go run ./examples/basic-app-react-ssr ``` -------------------------------- ### Install frontend dependencies Source: https://github.com/assurrussa/goinertia/blob/master/examples/basic-app-ssr/README.md Run this command to install the necessary npm packages for the Vue frontend. ```bash cd examples/basic-app-ssr npm install ``` -------------------------------- ### Run the Go server Source: https://github.com/assurrussa/goinertia/blob/master/examples/basic-app-react/README.md Run the Go server from the repo root. After starting, open http://localhost:8383. ```bash go run ./examples/basic-app-react ``` -------------------------------- ### Run Go server with Fiber or net/http adapter Source: https://github.com/assurrussa/goinertia/blob/master/examples/v3-app/README.md From the repository root, start the server with either the fiber or nethttp adapter. The -port flag sets the listening port. ```sh go run ./examples/v3-app -adapter fiber -port 8383 # Or: go run ./examples/v3-app -adapter nethttp -port 8383 ``` -------------------------------- ### Run the Go server Source: https://github.com/assurrussa/goinertia/blob/master/examples/basic-app/README.md Run this command from the repository root to start the Go server. The application will be available at http://localhost:8383. ```bash go run ./examples/basic-app ``` -------------------------------- ### Fiber root API setup with middleware and routes Source: https://github.com/assurrussa/goinertia/blob/master/README.md Initializes Inertia with validation, registers middleware, and defines a route that renders a component. Uses the Fiber root API; for native net/http see the net/http setup. ```go package main import ( "github.com/gofiber/fiber/v3" "github.com/assurrussa/goinertia" "github.com/assurrussa/goinertia/views" ) func main() { // 1. Initialize Inertia inertiaManager, err := goinertia.NewWithValidation("http://localhost:3000", goinertia.WithFS(views.Templates), goinertia.WithAssetVersion("v1"), goinertia.WithSharedProps(map[string]any{ "appName": "My App", }), // goinertia.WithDevMode(), // Use in development to enable hot-reloading ) if err != nil { panic(err) } // 2. Register Middleware app := fiber.New(fiber.Config{ErrorHandler: inertiaManager.MiddlewareErrorListener()}) // Handles Inertia requests, asset versioning, and validation redirects app.Use(inertiaManager.Middleware()) // 3. Define Routes app.Get("/", func(c fiber.Ctx) error { // Render a Vue/React component named "Home" return inertiaManager.Render(c, "Home", map[string]any{ "user": "John Doe", }) }) app.Listen(":3000") } ``` -------------------------------- ### Start Vite in dev mode (optional) Source: https://github.com/assurrussa/goinertia/blob/master/examples/basic-app/README.md Optionally, run this command to start Vite in development mode instead of building assets. This is useful for development with hot reload. ```bash npm run dev ``` -------------------------------- ### Basic goinertia setup with Fiber Source: https://github.com/assurrussa/goinertia/blob/master/docs/basic.md Initializes goinertia with validation, sets asset version and shared props, registers middleware, and renders a 'Home' page. Uses Fiber's error handler from the adapter. The default template uses the wire view of `.pageJSON`; `.page` and ScrollPropConfig keep their previous public field layouts. ```go package main import ( "github.com/gofiber/fiber/v3" "github.com/assurrussa/goinertia" ) func main() { inertiaAdapter, err := goinertia.NewWithValidation("http://localhost:3000", goinertia.WithAssetVersion("v1.0.0"), goinertia.WithSharedProps(map[string]any{ "appName": "My App", }), ) if err != nil { panic(err) } app := fiber.New(fiber.Config{ErrorHandler: inertiaAdapter.MiddlewareErrorListener()}) app.Use(inertiaAdapter.Middleware()) app.Get("/", func(c fiber.Ctx) error { return inertiaAdapter.Render(c, "Home", map[string]any{ "title": "Hello", }) }) _ = app.Listen(":3000") } ``` -------------------------------- ### Create net/http engine with v3 protocol and template FS Source: https://github.com/assurrussa/goinertia/blob/master/docs/inertia-v3.md Shows the full setup for a native net/http engine with v3 protocol and a template filesystem. Keep existing session, CSRF, template, and asset options. Returns an error that should be handled (e.g., panic). ```go import ( nethttp "github.com/assurrussa/goinertia/adapters/nethttp" "github.com/assurrussa/goinertia/core" "github.com/assurrussa/goinertia/views" ) // Keep the existing session, CSRF, template and asset options as well. manager, err := nethttp.NewWithValidation("http://localhost:3000", nethttp.WithCoreOptions( core.WithProtocolVersion(core.ProtocolV3), core.WithFS(views.Templates), // Or your application's template FS. ), ) if err != nil { panic(err) } ``` -------------------------------- ### Configure goinertia with Inertia v3 protocol Source: https://github.com/assurrussa/goinertia/blob/master/README.md Sets up the root Fiber import with the v3 protocol and a custom template FS. Add this to your existing setup; keep your existing assets, sessions, and CSRF options. ```go import ( "github.com/assurrussa/goinertia" "github.com/assurrussa/goinertia/views" ) inertiaManager, err := goinertia.NewWithValidation("http://localhost:3000", goinertia.WithProtocolVersion(goinertia.ProtocolV3), goinertia.WithFS(views.Templates), // Or your application's template FS. // Keep your existing assets, sessions and CSRF options here. ) if err != nil { panic(err) } ``` -------------------------------- ### Upgrade to goinertia v0.11.1 and install Inertia v3 frontend packages Source: https://github.com/assurrussa/goinertia/blob/master/README.md Upgrades the Go dependency to v0.11.1 for Inertia v3 support and installs the matching frontend package. Use @inertiajs/react@3.8.0 with React/ReactDOM 19+ for React instead of Vue. ```sh go get github.com/assurrussa/goinertia@v0.11.1 # In your Vue frontend directory: npm install --save-exact @inertiajs/vue3@3.8.0 # For React instead, use @inertiajs/react@3.8.0 and React/ReactDOM 19+. ``` -------------------------------- ### Run Go server with SSR URL for net/http Source: https://github.com/assurrussa/goinertia/blob/master/examples/v3-app/README.md Start the Go server with the -ssr-url flag pointing to the renderer's /render endpoint. The fiber adapter uses the same renderer and template. ```sh go run ./examples/v3-app -adapter nethttp -ssr-url http://127.0.0.1:13714/render # -adapter fiber uses the same renderer and template. ``` -------------------------------- ### Scroll Props Example Source: https://github.com/assurrussa/goinertia/blob/master/docs/lazy-props.md Shows how to use goinertia.Scroll with goinertia.ScrollPropConfig to add pagination metadata for infinite scroll. Scroll metadata emits reset: true when a reset occurs. ```go return inertia.Render(c, "Feed", map[string]any{ "posts": goinertia.Scroll(posts, goinertia.ScrollPropConfig{ PageName: "page", NextPage: 3, CurrentPage: 2, }), }) ``` -------------------------------- ### Implement custom SSRClient and configure with goinertia.WithSSRConfig Source: https://github.com/assurrussa/goinertia/blob/master/docs/ssr.md Shows how to implement the SSRClient interface for custom HTTP behavior (tracing, auth, custom transport) and pass it via SSRConfig. The example client uses http.DefaultClient and returns owned body bytes. Custom clients must support concurrent Post calls; retries do not call Reset. Cancellation, transport, status, and decoding errors remain errors; there is no automatic CSR fallback. ```go type mySSRClient struct{} func (c *mySSRClient) Reset() {} func (c *mySSRClient) Post(ctx context.Context, url string, body []byte, headers map[string]string) (int, []byte, error) { req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if err != nil { return 0, nil, err } for k, v := range headers { req.Header.Set(k, v) } resp, err := http.DefaultClient.Do(req) if err != nil { return 0, nil, err } defer resp.Body.Close() respBody, err := io.ReadAll(resp.Body) if err != nil { return 0, nil, err } return resp.StatusCode, respBody, nil } goinertia.WithSSRConfig(goinertia.SSRConfig{ URL: "http://127.0.0.1:13714/render", SSRClient: &mySSRClient{}, }) ``` -------------------------------- ### Merge Props Example Source: https://github.com/assurrussa/goinertia/blob/master/docs/lazy-props.md Shows how to use goinertia.Merge, goinertia.Prepend, and goinertia.DeepMerge to merge props during partial reloads. Merge props are merged during partial reloads (append or prepend for lists). ```go return inertia.Render(c, "Users", map[string]any{ "users": goinertia.Merge(users), "newest": goinertia.Prepend(newUsers), "profile": goinertia.DeepMerge(profile), }) ``` -------------------------------- ### Setting History Flags Source: https://github.com/assurrussa/goinertia/blob/master/docs/history.md Example of using the WithEncryptHistory and WithClearHistory methods to set history flags for the current response. ```APIDOC ## WithEncryptHistory ### Description Sets the `encryptHistory` flag for the current response, which encrypts stored history state on the client. ### Method Helper method on the `*goinertia.Inertia` instance. ### Parameters - `c` (fiber.Ctx) - Required - The Fiber context for the current request. ### Usage Example ```go inertia.WithEncryptHistory(c) ``` ## WithClearHistory ### Description Sets the `clearHistory` flag for the current response, which clears existing history state for the current visit. ### Method Helper method on the `*goinertia.Inertia` instance. ### Parameters - `c` (fiber.Ctx) - Required - The Fiber context for the current request. ### Usage Example ```go inertia.WithClearHistory(c) ``` ## Combined Usage ### Description Both flags can be set together for the same response. ### Usage Example ```go func Dashboard(c fiber.Ctx, inertia *goinertia.Inertia) error { inertia.WithEncryptHistory(c) inertia.WithClearHistory(c) return inertia.Render(c, "Dashboard", map[string]any{ "title": "Dashboard", }) } ``` ### Response The flags are emitted as `encryptHistory` and `clearHistory` in the page JSON. ``` -------------------------------- ### Go handler with goinertia validation and precognition support Source: https://github.com/assurrussa/goinertia/blob/master/docs/precognition.md Example Go handler that binds a request body, validates required fields, and renders a form. When the request includes Precognition headers, the response is validation-only. ```go func CreateUser(c fiber.Ctx, inertia *goinertia.Inertia) error { type CreateUserRequest struct { Name string `json:"name"` Email string `json:"email"` } var req CreateUserRequest if err := c.Bind().Body(&req); err != nil { inertia.WithError(c, "form", "Invalid payload") return inertia.Render(c, "Users/Create", map[string]any{}) } if req.Name == "" { inertia.WithError(c, "name", "Name is required") } if req.Email == "" { inertia.WithError(c, "email", "Email is required") } return inertia.Render(c, "Users/Create", map[string]any{}) } ``` -------------------------------- ### Run corrected Fiber benchmark Source: https://github.com/assurrussa/goinertia/blob/master/docs/benchmarks.md Runs the corrected Fiber benchmark in isolation with 10 counts. Use this to get a baseline result file for the corrected Fiber implementation. ```sh go test -run '^$' -bench '^BenchmarkCorrectedFiber$' -benchmem -count=10 ./ ``` -------------------------------- ### Customize SSR retry behavior with MaxRetries, RetryDelay, RetryStatuses Source: https://github.com/assurrussa/goinertia/blob/master/docs/ssr.md Configures custom retry parameters: maximum retry count, delay between retries, and which HTTP status codes trigger a retry. The example uses 2 retries, a 50ms delay, and retries on 429 and 503 statuses. ```go goinertia.WithSSRConfig(goinertia.SSRConfig{ URL: "http://127.0.0.1:13714/render", MaxRetries: 2, RetryDelay: 50 * time.Millisecond, RetryStatuses: []int{http.StatusTooManyRequests, http.StatusServiceUnavailable}, }) ``` -------------------------------- ### Build the client bundle Source: https://github.com/assurrussa/goinertia/blob/master/examples/basic-app/README.md Run this command to build the client bundle for production. This is required before running the Go server. ```bash npm run build ``` -------------------------------- ### Run the Go server Source: https://github.com/assurrussa/goinertia/blob/master/examples/basic-app-ssr/README.md Run the Go backend server from the repository root. ```bash go run ./examples/basic-app-ssr ``` -------------------------------- ### Enable Inertia v3 with nethttp.New and core.WithProtocolVersion Source: https://github.com/assurrussa/goinertia/blob/master/docs/inertia-v3.md Explicitly opt into the Inertia v3 protocol when creating a net/http adapter. V2 remains the default; enable v3 only when the browser bundle has also migrated. Configure the engine before serving and never change the protocol concurrently. ```go inertia := nethttp.New("https://app.example", nethttp.WithCoreOptions(core.WithProtocolVersion(core.ProtocolV3)), ) ``` -------------------------------- ### Initialize goinertia with SSR config Source: https://github.com/assurrussa/goinertia/blob/master/docs/ssr.md Use WithSSRConfig to provide the SSR server URL and optional settings like timeout and cache. The default port is 13714. ```go inertiaAdapter := goinertia.Must(goinertia.NewWithValidation("http://localhost:3000", // ... other options goinertia.WithSSRConfig(goinertia.SSRConfig{ // The URL of your Node.js SSR server (default port is 13714) URL: "http://127.0.0.1:13714/render", // Optional: request timeout Timeout: 3 * time.Second, // Optional: SSR cache settings CacheTTL: 5 * time.Minute, CacheMaxEntries: 1024, }), )) ``` -------------------------------- ### Build the client and SSR bundles Source: https://github.com/assurrussa/goinertia/blob/master/examples/basic-app-react-ssr/README.md Run these commands to build the client and SSR bundles. The optional dev:ssr command rebuilds the SSR bundle on changes. ```bash npm run build npm run build:ssr ``` ```bash npm run dev:ssr ``` -------------------------------- ### Run all comparison benchmarks Source: https://github.com/assurrussa/goinertia/blob/master/docs/benchmarks.md Runs the full set of comparison benchmarks (CorrectedFiber, NativeFiber, NativeHTTP, FiberMetadataOwnership) with 10 counts. Save separate result files for each scenario and compare with benchstat. ```sh go test -run '^$' -bench '^Benchmark(CorrectedFiber|NativeFiber|NativeHTTP|FiberMetadataOwnership)$' -benchmem -count=10 ./ ``` -------------------------------- ### Run tests (make test) Source: https://github.com/assurrussa/goinertia/blob/master/CONTRIBUTING.md Runs the test suite. ```bash make test ``` -------------------------------- ### Run a single profile Source: https://github.com/assurrussa/goinertia/blob/master/integration/browser/README.md Commands to build and verify a single profile. Sets INERTIA_VERSION and FRAMEWORK environment variables, then runs build, verify:ssr, and npm test. ```sh INERTIA_VERSION=3.8.0 FRAMEWORK=react npm run build npm run verify:ssr npm test ``` -------------------------------- ### Format code (make fmt) Source: https://github.com/assurrussa/goinertia/blob/master/CONTRIBUTING.md Applies go fmt, gofumpt, and gci to format imports and code style. ```bash make fmt ``` -------------------------------- ### Build SSR bundle Source: https://github.com/assurrussa/goinertia/blob/master/examples/basic-app-ssr/README.md Build the server-side rendering bundle for the Vue app. ```bash npm run build:ssr ``` -------------------------------- ### Run all checks (make check) Source: https://github.com/assurrussa/goinertia/blob/master/CONTRIBUTING.md Runs generate, format, lint, and test. This is the default goal and should be run before submitting a pull request. ```bash make check ``` -------------------------------- ### MergeAt with AppendAt and PrependAt Source: https://github.com/assurrussa/goinertia/blob/master/docs/lazy-props.md Shows how to use core.MergeAt to add independent append/prepend targets. Paths are relative to the root prop and traverse JSON maps; an empty path targets the root. The optional matching field is relative to each array item. On a prop named 'users', it emits users.data, users.older, and matching paths users.data.id, users.older.id. Untargeted fields are replaced by the client. ```go core.MergeAt(map[string]any{ "data": users, "older": olderUsers, "total": total, }, core.AppendAt("data", "id"), core.PrependAt("older", "id")) ``` -------------------------------- ### Run the pinned client protocol replay test Source: https://github.com/assurrussa/goinertia/blob/master/integration/protocol-replay/README.md Executes the Go test that replays Inertia client methods against real server responses. Requires Node 24 and the GOINERTIA_CLIENT_REPLAY environment variable set to 1. The test fails if Node is missing and runs with a bounded timeout. ```sh GOINERTIA_CLIENT_REPLAY=1 go test -run '^TestPinnedClientProtocolReplay$' -count=1 ./ ``` -------------------------------- ### Register Session Store with Fiber Adapter Source: https://github.com/assurrussa/goinertia/blob/master/docs/redirect-409.md Pass the session adapter during initialization to preserve flash messages across redirects. Uses goinertia.NewFiberSessionAdapter with a session store and the WithSessionStore option. ```go store := session.New() sessionAdapter := goinertia.NewFiberSessionAdapter[*session.Session](store) inertiaAdapter := goinertia.New("http://localhost:8080", goinertia.WithSessionStore(sessionAdapter), // ... other options ) ``` -------------------------------- ### Using WithNativeFlash with Fiber and legacy flash Source: https://github.com/assurrussa/goinertia/blob/master/docs/flash.md Demonstrates the native flash API on Fiber, adding a JSON-serializable value under a key to the top-level page.flash object. Also shows using the compatible legacy flash independently in the same response. The native flash is included regardless of partial prop selection. ```go inertia.WithNativeFlash(c, "toast", map[string]any{ "type": "success", "message": "Profile saved", }) inertia.WithFlashSuccess(c, "Compatible legacy message") // optional, independent return inertia.Redirect(c, "/profile") ``` -------------------------------- ### Once prop with goinertia.Once Source: https://github.com/assurrussa/goinertia/blob/master/docs/lazy-props.md Defines a once prop 'plans' that is sent once and then skipped on subsequent requests unless explicitly refreshed, using a custom key 'plans_v1'. ```go return inertia.Render(c, "Dashboard", map[string]any{ "plans": goinertia.Once("basic", goinertia.WithOnceKey("plans_v1")), }) ``` -------------------------------- ### Using WithNativeFlash with net/http Source: https://github.com/assurrussa/goinertia/blob/master/docs/flash.md Shows the native flash API for the net/http adapter. Adds a native flash value and redirects. The native flash is included independently of partial prop selection. ```go inertia.WithNativeFlash(nethttp.State(r), "message", "Profile saved") return inertia.Redirect(w, r, "/profile") ``` -------------------------------- ### Configure GoInertia with shared lazy props Source: https://github.com/assurrussa/goinertia/blob/master/docs/shared-lazy.md Creates a new GoInertia adapter with shared props that are lazily evaluated. Each LazyProp has a Key and a Fn function that returns the prop value. The Fn functions are called only when the prop is requested, allowing for efficient loading of data like auth and notifications. ```go inertiaAdapter := goinertia.New("http://localhost:3000", goinertia.WithSharedProps(map[string]any{ "auth": goinertia.LazyProp{ Key: "auth", Fn: func(ctx context.Context) (any, error) { return loadAuth(), nil }, }, "notifications": goinertia.LazyProp{ Key: "notifications", Fn: func(ctx context.Context) (any, error) { return loadNotifications(), nil }, }, }), ) ``` -------------------------------- ### Handle file uploads with goinertia.ProcessFileUploads Source: https://github.com/assurrussa/goinertia/blob/master/docs/uploads.md Defines a Fiber handler that processes uploaded files using goinertia's ProcessFileUploads. It sets a 5 MB limit, allows .jpg, .jpeg, .png, and .pdf extensions, and stores files in the 'uploads' directory. On error, it flashes an error and redirects back; on validation errors, it renders the form with errors; on success, it flashes success and redirects to /files. ```go func UploadFiles(c fiber.Ctx, inertia *goinertia.Inertia) error { config := &goinertia.FileUploadConfig{ MaxFileSize: 5 * 1024 * 1024, AllowedExtensions: []string{".jpg", ".jpeg", ".png", ".pdf"}, UploadDir: "uploads", } result, err := inertia.ProcessFileUploads(c, "files", config) if err != nil { inertia.WithFlashError(c, "Upload failed") return inertia.RedirectBack(c) } if len(result.Errors) > 0 { inertia.WithFileUploadErrors(c, result) return inertia.Render(c, "Upload/Form", map[string]any{ "title": "Upload", }) } inertia.WithFileUploadSuccess(c, result.Files) return inertia.Redirect(c, "/files") } ``` -------------------------------- ### Run tests with race detector (make test-race) Source: https://github.com/assurrussa/goinertia/blob/master/CONTRIBUTING.md Runs tests with the race detector enabled. ```bash make test-race ``` -------------------------------- ### SSR configuration with WithSSRConfig Source: https://github.com/assurrussa/goinertia/blob/master/README.md Enables server-side rendering by communicating with a Node.js Inertia SSR server. Configures URL, timeout, cache, retries, and retry statuses. ```go inertiaManager := goinertia.Must(goinertia.NewWithValidation(url, goinertia.WithSSRConfig(goinertia.SSRConfig{ URL: "http://127.0.0.1:13714/render", // or goinertia.DefaultSSRURL, Timeout: 3 * time.Second, CacheTTL: 5 * time.Minute, CacheMaxEntries: 1024, MaxRetries: 2, RetryDelay: 50 * time.Millisecond, RetryStatuses: []int{http.StatusTooManyRequests, http.StatusServiceUnavailable}, // DisableRetries: true, // SSRClient: createClient..., }), )) ``` -------------------------------- ### Run pinned v2.3.18 client protocol replay Source: https://github.com/assurrussa/goinertia/blob/master/docs/protocol-coverage.md Command to run the focused pinned v2.3.18 client replay separately. It covers grouped deferred scheduling, preservation of an excluded deep-merge prop, paginator append/prepend and scroll reset. ```sh GOINERTIA_CLIENT_REPLAY=1 go test -run '^TestPinnedClientProtocolReplay$' ./ ``` -------------------------------- ### Flash messages and validation redirects Source: https://github.com/assurrussa/goinertia/blob/master/README.md Shows how to set flash errors and success messages after form submissions. Requires WithSessionStore to be configured. Uses WithFlashError, WithError, RedirectBack, WithFlashSuccess, and Redirect. ```go // In your controller if err := validate(form); err != nil { inertiaManager.WithFlashError(ctx, "Something went wrong.") inertiaManager.WithError(ctx, "email", "Email is already taken.") return inertiaManager.RedirectBack(ctx) } inertiaManager.WithFlashSuccess(ctx, "Profile updated!") return inertiaManager.Redirect(ctx, "/profile") ``` -------------------------------- ### Serialize page with native flash using core.MarshalPageWithState Source: https://github.com/assurrussa/goinertia/blob/master/docs/flash.md Use this Go snippet to build a page with native flash and serialize it with the request state, ensuring the flash is included in the wire format. This is required because json.Marshal(page) and core.MarshalPage(page, resetHeader) do not include native flash. ```go engine.WithNativeFlash(state, "message", "Saved") page, err := engine.BuildPage(state, "Profile", props) if err != nil { return err } body, err := core.MarshalPageWithState(page, state) ``` -------------------------------- ### Run independent HTTP consumer checks Source: https://github.com/assurrussa/goinertia/blob/master/docs/protocol-coverage.md Commands to run from the integration/nethttp-consumer directory to verify the module's dependencies and tests. The compiled/test graph must not contain gofiber or fasthttp packages. ```sh go mod tidy go vet ./... go build ./... go test -race -count=5 ./... go list -deps -test ./... > dependencies.txt ``` -------------------------------- ### Once Source: https://github.com/assurrussa/goinertia/blob/master/docs/lazy-props.md Documentation for the Once function and its options for sending remembered values with freshness and composition. ```APIDOC ## Once ### Description Sends a remembered value again. Freshness never bypasses selection, optional omission or deferred loading. ### Signature Once(value, WithOnceFresh()) ### Parameters - **value** (any) - Required - The value to send. - **options** (OnceOption) - Optional - Configuration options. ### Options - **WithOnceFresh()** - Sends a remembered value again; pass `WithOnceFresh(false)` to turn it off. - **WithOnceKey** - Configures client identity. - **WithOnceExpiresAt** - Configures expiry (Unix milliseconds). - **WithOnceRefreshOnPartial()** - Opts into the official v2 reference adapter's selected-partial refresh policy. This refreshes selected Once values on both only and except requests. A matching component alone still does not make a request partial: this adapter requires a nonempty only/except filter. ### Behavior - Legacy behavior is preserved: an explicit `only` selection refreshes a remembered Once prop, while an except-only request does not. - The existing Except-Once header policy also remains unchanged: if supplied on a non-Inertia HTML request, it still participates in remembered-value omission. The pinned PHP reference restricts that omission to Inertia JSON requests. - One Once wrapper can compose in either order with `Defer`, `Optional`, `Merge`, `Prepend`, `DeepMerge` and `MergeAt` in a top-level wrapper chain. This is not recursive wrapper interpretation inside map/array values. - Initial deferred or optional values remain omitted, with Once registration retained. - Remembered Once+deferred values do not announce another deferred request; freshness re-enables the announcement. - Once metadata intentionally remains when a cached value is omitted, unlike merge metadata, which requires resolved data. ``` -------------------------------- ### Render method for Inertia response Source: https://github.com/assurrussa/goinertia/blob/master/README.md Returns an Inertia response. For XHR requests it returns JSON; otherwise it renders the root HTML template. ```go inertiaManager.Render(ctx, "Dashboard/Index", map[string]any{ "stats": statsData, }) ``` -------------------------------- ### Lint code (make lint) Source: https://github.com/assurrussa/goinertia/blob/master/CONTRIBUTING.md Uses golangci-lint to check for code quality issues. ```bash make lint ``` -------------------------------- ### Deferred prop with goinertia.Defer Source: https://github.com/assurrussa/goinertia/blob/master/docs/lazy-props.md Defines a deferred prop 'heavy' that is not included in the initial response and is loaded later via a partial reload. ```go return inertia.Render(c, "Dashboard", map[string]any{ "heavy": goinertia.Defer(goinertia.LazyProp{ Key: "heavy", Fn: func(ctx context.Context) (any, error) { return loadHeavyData(), nil }, }), }) ``` -------------------------------- ### Optional prop with goinertia.Optional Source: https://github.com/assurrussa/goinertia/blob/master/docs/lazy-props.md Defines an optional prop 'metrics' that is omitted on full visits and resolved on a matching partial reload when selected by only or not excluded by except. ```go return inertia.Render(c, "Dashboard", map[string]any{ "metrics": goinertia.Optional(goinertia.LazyProp{ Key: "metrics", Fn: func(ctx context.Context) (any, error) { return loadMetrics(), nil }, }), }) ``` -------------------------------- ### Using WithFlashError and WithFlashSuccess in a Fiber handler Source: https://github.com/assurrussa/goinertia/blob/master/docs/flash.md Shows how to use the compatible flash helpers in a Fiber handler. On error, sets a flash error and redirects back; on success, sets a flash success and redirects back. These helpers do not trigger the native Inertia flash event. ```go func ProcessAction(c fiber.Ctx, inertia *goinertia.Inertia) error { if err := save(); err != nil { inertia.WithFlashError(c, "Save failed") return inertia.RedirectBack(c) } inertia.WithFlashSuccess(c, "Saved") return inertia.RedirectBack(c) } ``` -------------------------------- ### goinertia.WithSSRFailureHandler for v3 SSR failure reporting Source: https://github.com/assurrussa/goinertia/blob/master/docs/ssr.md Configure a callback that runs once per failed SSR render, after retries conclude)Skip that attempt. The callback must be concurrency-safe; use errors.As to extract *core.SSRResponseError for v3 renderer error details. Runs also when propagation is selected, but not for cancelled requests. ```go goinertia.WithSSRFailureHandler(func(ctx context.Context, err error) { // Report to your error tracker. errors.As(err, &detail) can recover // *core.SSRResponseError: status, message, type, hint, browser API, // stack, and source location from a v3 renderer's error response. }) ``` -------------------------------- ### External Redirect (Go) Source: https://github.com/assurrussa/goinertia/blob/master/docs/redirect-409.md Uses inertia.RedirectExternal to redirect to an external domain, triggering a full reload. ```go func (c *Controller) Logout(ctx fiber.Ctx) error { return c.inertia.RedirectExternal(ctx, "https://example.com") } ``` -------------------------------- ### Disable Vary: Precognition header with goinertia.WithPrecognitionVary Source: https://github.com/assurrussa/goinertia/blob/master/docs/precognition.md By default, responses include the Vary: Precognition header per protocol. Call goinertia.WithPrecognitionVary(false) to disable it. ```go goinertia.WithPrecognitionVary(false) ``` -------------------------------- ### Once Source: https://github.com/assurrussa/goinertia/blob/master/docs/lazy-props.md Creates a once prop that is sent once and then skipped on subsequent requests unless explicitly refreshed. ```APIDOC ## Once ### Description Creates a once prop that is sent once and then skipped on subsequent requests unless explicitly refreshed. ### Method Once ### Signature func Once(key string, opts ...Option) any ### Parameters - **key** (string) - Required - The prop key. - **opts** (Option) - Optional - Options such as WithOnceKey. ### Example ```go return inertia.Render(c, "Dashboard", map[string]any{ "plans": goinertia.Once("basic", goinertia.WithOnceKey("plans_v1")), }) ``` ``` -------------------------------- ### Detect precognition request with goinertia.IsPrecognition Source: https://github.com/assurrussa/goinertia/blob/master/docs/precognition.md Use goinertia.IsPrecognition(c) to detect Precognition requests early and skip side effects, only collecting validation errors. ```go if goinertia.IsPrecognition(c) { // skip side effects; just collect errors } ``` -------------------------------- ### Redirect (net/http) Source: https://github.com/assurrussa/goinertia/blob/master/docs/flash.md Redirects to a given URL. This is the native HTTP API variant. ```APIDOC ## Redirect (net/http) ### Description Redirects to a given URL. This is the native HTTP API variant. ### Method Function ### Signature `func (i *Inertia) Redirect(w http.ResponseWriter, r *http.Request, url string) error` ### Parameters - **w** (http.ResponseWriter) - Required - The HTTP response writer. - **r** (*http.Request) - Required - The HTTP request. - **url** (string) - Required - The destination URL. ### Example ```go return inertia.Redirect(w, r, "/profile") ``` ``` -------------------------------- ### Defer Source: https://github.com/assurrussa/goinertia/blob/master/docs/lazy-props.md Creates a deferred prop that is not included in the initial response and is loaded later via a partial reload. ```APIDOC ## Defer ### Description Creates a deferred prop that is not included in the initial response and is loaded later via a partial reload. ### Method Defer ### Signature func Defer(prop LazyProp) any ### Parameters - **prop** (LazyProp) - Required - The lazy prop definition containing Key and Fn. ### Example ```go return inertia.Render(c, "Dashboard", map[string]any{ "heavy": goinertia.Defer(goinertia.LazyProp{ Key: "heavy", Fn: func(ctx context.Context) (any, error) { return loadHeavyData(), nil }, }), }) ``` ``` -------------------------------- ### WithFlashSuccess Source: https://github.com/assurrussa/goinertia/blob/master/docs/flash.md Stores a string success message in the legacy `page.props.flash` object. This is part of the compatible `WithFlash` helpers that retain ordinary `page.props.flash` behavior. ```APIDOC ## WithFlashSuccess ### Description Stores a string success message in the legacy `page.props.flash` object. This is part of the compatible `WithFlash` helpers that retain ordinary `page.props.flash` behavior. ### Method Function ### Signature `func (i *Inertia) WithFlashSuccess(c fiber.Ctx, message string) error` ### Parameters - **c** (fiber.Ctx) - Required - The Fiber context. - **message** (string) - Required - The success message to store. ### Example ```go inertia.WithFlashSuccess(c, "Saved") ``` ### Notes - Does not trigger the native Inertia flash event. - Not automatically migrated to native flash. ``` -------------------------------- ### WithNativeFlash (net/http) Source: https://github.com/assurrussa/goinertia/blob/master/docs/flash.md Adds a JSON-serializable value under an arbitrary key to the separate, top-level `page.flash` object. This is the native HTTP API variant. ```APIDOC ## WithNativeFlash (net/http) ### Description Adds a JSON-serializable value under an arbitrary key to the separate, top-level `page.flash` object. This is the native HTTP API variant. ### Method Function ### Signature `func (i *Inertia) WithNativeFlash(r *http.Request, key string, value any) error` ### Parameters - **r** (*http.Request) - Required - The HTTP request. - **key** (string) - Required - The key under which the value is stored in `page.flash`. - **value** (any) - Required - The JSON-serializable value to store. ### Example ```go inertia.WithNativeFlash(nethttp.State(r), "message", "Profile saved") ``` ### Notes - Values are data, not lazy/prop-wrapper callbacks. - Both flash APIs may be used in the same response without overwriting each other. - Without native data, the top-level field is omitted, preserving the legacy response shape. - Native flash is included independently of partial `only`/`except` prop selection. - Current-request keys override session keys. - Default HTML bootstrap, JSON responses and SSR receive the same native flash and scroll-reset metadata. ``` -------------------------------- ### Custom Inertia v3 root template using .inertiaHead and .inertiaBody Source: https://github.com/assurrussa/goinertia/blob/master/docs/ssr.md For custom root templates with Inertia v3, renders the head and body from the shared template variables without adding a second script or mount point. The head tags use data-inertia, and on CSR responses .inertiaBody generates the v3 script tag with an empty app div. ```html {{ .inertiaHead }} {{ .inertiaBody }} ``` -------------------------------- ### Optional Source: https://github.com/assurrussa/goinertia/blob/master/docs/lazy-props.md Creates an optional prop that is omitted on full visits and resolved on a matching partial reload when selected by only or not excluded by except. ```APIDOC ## Optional ### Description Creates an optional prop that is omitted on full visits and resolved on a matching partial reload when selected by only or not excluded by except. ### Method Optional ### Signature func Optional(prop LazyProp) any ### Parameters - **prop** (LazyProp) - Required - The lazy prop definition containing Key and Fn. ### Example ```go return inertia.Render(c, "Dashboard", map[string]any{ "metrics": goinertia.Optional(goinertia.LazyProp{ Key: "metrics", Fn: func(ctx context.Context) (any, error) { return loadMetrics(), nil }, }), }) ``` ``` -------------------------------- ### MergeAt Source: https://github.com/assurrussa/goinertia/blob/master/docs/lazy-props.md Documentation for the MergeAt function, which adds independent append/prepend targets for merging props. ```APIDOC ## MergeAt ### Description Adds independent append/prepend targets without changing MergeProp or the existing Merge, Prepend and DeepMerge constructors. Paths are relative to the root prop and traverse JSON maps; an empty path targets the root. The optional matching field is relative to each array item. ### Signature core.MergeAt(map[string]any, core.AppendAt("data", "id"), core.PrependAt("older", "id")) ### Parameters - **targets** (map[string]any) - Required - Map of target paths to values. - **appendTargets** (core.AppendAt) - Required - Append target with path and matching field. - **prependTargets** (core.PrependAt) - Required - Prepend target with path and matching field. ### Behavior - Paths are relative to the root prop and traverse JSON maps; an empty path targets the root. - The optional matching field is relative to each array item. - On a prop named `users`, the example emits `users.data`, `users.older`, and matching paths `users.data.id`, `users.older.id`. - Untargeted fields are replaced by the client. - No implicit root merge label is added. - Configure each target once. - Metadata is emitted only for target paths present in successfully resolved, selected data. - A `MergeAt` value replaces lower-precedence data and wrapper metadata; if its callback fails, that root is omitted instead of reusing a lower-layer value. - A reset of the root prop suppresses all its wrapper merge and matching labels. - `Defer(MergeAt(...))` and `MergeAt(Defer(...), ...)` are supported. - Arrays may be typed; path traversal itself does not use reflection. ### Example ```go core.MergeAt(map[string]any{ "data": users, "older": olderUsers, "total": total, }, core.AppendAt("data", "id"), core.PrependAt("older", "id")) ``` ``` -------------------------------- ### Lazy evaluation with WithLazyProp Source: https://github.com/assurrussa/goinertia/blob/master/README.md Wraps expensive data so it is only executed when the client explicitly requests it via a partial reload. ```go inertiaManager.WithLazyProp(ctx, "heavyData", func (c context.Context) (any, error) { return heavyDatabaseQuery(), nil }) ``` -------------------------------- ### WithNativeFlash for opt-in native flash events Source: https://github.com/assurrussa/goinertia/blob/master/README.md Use WithNativeFlash to opt into native Inertia flash events and history exclusion. The existing helpers keep compatible props.flash behavior. ```go inertiaManager.WithNativeFlash(ctx, "message", "Profile updated!") ``` -------------------------------- ### Update root template (app.gohtml) for SSR Source: https://github.com/assurrussa/goinertia/blob/master/docs/ssr.md The template uses the .processSSR variable to render head tags and pre-rendered body. If SSR fails or is disabled, it falls back to the regular CSR container. ```html {{/* 1. Render meta tags and head content from SSR */}} {{ if .processSSR }} {{ range .processSSR.Head }} {{ raw . }} {{ end }} {{ end }} {{/* ... your scripts and styles ... */}} {{/* 2. Render pre-rendered HTML body if available. Note: The SSR body includes the root element (e.g.,
). If SSR fails or is disabled, fallback to regular CSR container. */}} {{ if .processSSR }} {{ raw .processSSR.Body }} {{ else }}
{{ end }} ``` -------------------------------- ### RedirectBack Source: https://github.com/assurrussa/goinertia/blob/master/docs/flash.md Redirects back to the previous page. Used in conjunction with flash helpers to provide feedback after an action. ```APIDOC ## RedirectBack ### Description Redirects back to the previous page. Used in conjunction with flash helpers to provide feedback after an action. ### Method Function ### Signature `func (i *Inertia) RedirectBack(c fiber.Ctx) error` ### Parameters - **c** (fiber.Ctx) - Required - The Fiber context. ### Example ```go return inertia.RedirectBack(c) ``` ``` -------------------------------- ### WithNativeFlash (Fiber) Source: https://github.com/assurrussa/goinertia/blob/master/docs/flash.md Adds a JSON-serializable value under an arbitrary key to the separate, top-level `page.flash` object. Supports strings, objects, arrays, booleans and null values. Calling it again with the same key replaces that key; other keys are retained. ```APIDOC ## WithNativeFlash (Fiber) ### Description Adds a JSON-serializable value under an arbitrary key to the separate, top-level `page.flash` object. Supports strings, objects, arrays, booleans and null values. Calling it again with the same key replaces that key; other keys are retained. ### Method Function ### Signature `func (i *Inertia) WithNativeFlash(c fiber.Ctx, key string, value any) error` ### Parameters - **c** (fiber.Ctx) - Required - The Fiber context. - **key** (string) - Required - The key under which the value is stored in `page.flash`. - **value** (any) - Required - The JSON-serializable value to store. ### Example ```go inertia.WithNativeFlash(c, "toast", map[string]any{ "type": "success", "message": "Profile saved", }) ``` ### Notes - Values are data, not lazy/prop-wrapper callbacks. - Both flash APIs may be used in the same response without overwriting each other. - Without native data, the top-level field is omitted, preserving the legacy response shape. - Native flash is included independently of partial `only`/`except` prop selection. - Current-request keys override session keys. - Default HTML bootstrap, JSON responses and SSR receive the same native flash and scroll-reset metadata. ``` -------------------------------- ### Rebuild SSR bundle on changes Source: https://github.com/assurrussa/goinertia/blob/master/examples/basic-app-ssr/README.md Optional: Automatically rebuild the SSR bundle when files change during development. ```bash npm run dev:ssr ```