Gonertia is a well-tested and zero-dependency Inertia.js server-side adapter for Golang. Visit inertiajs.com to learn more.
Inertia allows you to create fully client-side rendered single-page apps without the complexity that comes with modern SPAs. It does this by leveraging existing server-side patterns that you already love.
This package based on the official Laravel adapter for Inertia.js inertiajs/inertia-laravel, supports all the features and works in the most similar way.
- Tests
- Helpers for testing
- Helpers for validation errors
- Examples
- SSR
- Inertia 2.0 compatibility
Install using go get command:
go get github.com/romsar/gonertia/v2Initialize Gonertia in your main.go:
package main
import (
"log"
"net/http"
inertia "github.com/romsar/gonertia"
)
func main() {
i, err := inertia.New(rootHTMLString)
// i, err := inertia.NewFromFile("resources/views/root.html")
// i, err := inertia.NewFromFileFS(embedFS, "resources/views/root.html")
// i, err := inertia.NewFromReader(rootHTMLReader)
// i, err := inertia.NewFromBytes(rootHTMLBytes)
if err != nil {
log.Fatal(err)
}
// Now create your HTTP server.
// Gonertia works well with standard http server library,
// but you are free to use some external routers like Gorilla Mux or Chi.
mux := http.NewServeMux()
mux.Handle("/home", i.Middleware(homeHandler(i)))
}
func homeHandler(i *inertia.Inertia) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
err := i.Render(w, r, "Home/Index", inertia.Props{
"some": "data",
})
if err != nil {
handleServerErr(w, err)
return
}
}
return http.HandlerFunc(fn)
}Create root.html template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- Put here your styles, meta and other stuff -->
{{ .inertiaHead }}
</head>
<body>
{{ .inertia }}
<script type="module" src="/build/assets/app.js"></script>
</body>
</html>- Gonertia + Vue + Vite + Tailwind
- Gonertia + Svelte + Vite + Tailwind
- Gonertia + React + Vite + Tailwind
- Also you can use Alpacaproj project generator
Set asset version (learn more)
i, err := inertia.New(
/* ... */
inertia.WithVersion("some-version"), // by any string
inertia.WithVersionFromFile("./public/build/manifest.json"), // by file checksum
inertia.WithVersionFromFileFS(embedFS, "./public/build/manifest.json"), // by file checksum from fs.FS
)SSR (Server Side Rendering) (learn more)
To enable server side rendering you have to provide an option in place where you initialize Gonertia:
i, err := inertia.New(
/* ... */
inertia.WithSSR(), // default is http://127.0.0.1:13714
inertia.WithSSR("http://127.0.0.1:1234"), // custom url http://127.0.0.1:1234
)Also, you have to use asset bundling tools like Vite or Webpack (especially with Laravel Mix). The setup will vary depending on this choice, you can read more about it in official docs or check an example that works on Vite.
Optional and Always props (learn more)
props := inertia.Props{
"optional": inertia.Optional{func () (any, error) {
return "prop", nil
}},
"always": inertia.Always("prop"),
}
i.Render(w, r, "Some/Page", props)Merging props (learn more)
props := inertia.Props{
"merging": inertia.Merge([]int{rand.Int63()}),
}Deferred props (learn more)
props := inertia.Props{
"defer_with_default_group": inertia.Defer(func () (any, error) {
return "prop", nil
}),
"defer_with_custom_group": inertia.Defer("prop", "foobar"),
"defer_with_merging": inertia.Defer([]int64{rand.Int63()}).Merge(),
}Once props (learn more)
Gonertia supports light version of Once props (feel free to send a pr with support of other features).
props := inertia.Props{
"foo": inertia.Once("bar"),
}Infinite scrolling (learn more)
props := inertia.Props{
// Basic scroll prop (defaults to "data" wrapper)
"items": inertia.Scroll(items),
// Scroll prop with custom wrapper
"results": inertia.Scroll(items, inertia.WithWrapper("results")),
// Scroll prop with pagination metadata
"posts": inertia.Scroll(posts, inertia.WithMetadata(inertia.ScrollMetadata{
PageName: "page",
PreviousPage: 1,
NextPage: 3,
CurrentPage: 2,
})),
// Scroll prop with metadata function (extracts metadata from your data structure)
"articles": inertia.Scroll(paginatedData, inertia.WithMetadataFunc(
func(data PaginatedData) inertia.ProvidesScrollMetadata {
return inertia.ScrollMetadata{
PageName: "page",
CurrentPage: data.CurrentPage,
NextPage: data.NextPage,
PreviousPage: data.PrevPage,
}
},
)),
}Redirects (learn more)
i.Redirect(w, r, "https://example.com") // plain redirect
i.Location(w, r, "https://example.com") // external redirectNOTES: If response is empty - user will be redirected to the previous url, just like in Laravel official adapter.
To manually redirect back, you can use Back helper:
i.Back(w, r)Share template data (learn more)
i.ShareTemplateData("title", "Home page")<h1>{{ .title }}</h1>i.ShareTemplateFunc("trim", strings.TrimSpace)<h1>{{ trim " foo bar " }}</h1>ctx := inertia.SetTemplateData(r.Context(), inertia.TemplateData{"foo", "bar"})
// or inertia.SetTemplateDatum(r.Context(), "foo", "bar")
// pass it to the next middleware or inertia.Render function using r.WithContext(ctx).Share prop globally (learn more)
i.ShareProp("foo", "bar")ctx := inertia.SetProps(r.Context(), inertia.Props{"foo": "bar"})
// or inertia.SetProp(r.Context(), "foo", "bar")
// pass it to the next middleware or inertia.Render function using r.WithContext(ctx).Validation errors (learn more)
ctx := inertia.SetValidationErrors(r.Context(), inertia.ValidationErrors{"some_field": "some error"})
// or inertia.AddValidationErrors(r.Context(), inertia.ValidationErrors{"some_field": "some error"})
// or inertia.SetValidationError(r.Context(), "some_field", "some error")
// pass it to the next middleware or inertia.Render function using r.WithContext(ctx).- Implement JSONMarshaller interface:
import jsoniter "github.com/json-iterator/go"
type jsonIteratorMarshaller struct{}
func (j jsonIteratorMarshaller) Decode(r io.Reader, v any) error {
return jsoniter.NewDecoder(r).Decode(v)
}
func (j jsonIteratorMarshaller) Marshal(v any) ([]byte, error) {
return jsoniter.Marshal(v)
}- Provide your implementation in constructor:
i, err := inertia.New(
/* ... */,
inertia.WithJSONMarshaller(jsonIteratorMarshaller{}),
)i, err := inertia.New(
/* ... */
inertia.WithLogger(), // default logger
// inertia.WithLogger(somelogger.New()),
)i, err := inertia.New(
/* ... */
inertia.WithContainerID("inertia"),
)Unfortunately (or fortunately) we do not have the advantages of such a framework as Laravel in terms of session management. In this regard, we have to do some things manually that are done automatically in frameworks.
One of them is displaying validation errors after redirects.
You have to write your own implementation of gonertia.FlashProvider which will have to store error data into the user's session and return this data (you can get the session ID from the context depending on your application).
i, err := inertia.New(
/* ... */
inertia.WithFlashProvider(flashProvider),
)Simple inmemory implementation of flash provider:
type InmemFlashProvider struct {
errors map[string]inertia.ValidationErrors
clearHistory map[string]bool
}
func NewInmemFlashProvider() *InmemFlashProvider {
return &InmemFlashProvider{errors: make(map[string]inertia.ValidationErrors)}
}
func (p *InmemFlashProvider) FlashErrors(ctx context.Context, errors ValidationErrors) error {
sessionID := getSessionIDFromContext(ctx)
p.errors[sessionID] = errors
return nil
}
func (p *InmemFlashProvider) GetErrors(ctx context.Context) (ValidationErrors, error) {
sessionID := getSessionIDFromContext(ctx)
errors := p.errors[sessionID]
delete(p.errors, sessionID)
return errors, nil
}
func (p *InmemFlashProvider) FlashClearHistory(ctx context.Context) error {
sessionID := getSessionIDFromContext(ctx)
p.clearHistory[sessionID] = true
return nil
}
func (p *InmemFlashProvider) ShouldClearHistory(ctx context.Context) (bool, error) {
sessionID := getSessionIDFromContext(ctx)
clearHistory := p.clearHistory[sessionID]
delete(p.clearHistory, sessionID)
return clearHistory
}History encryption (learn more)
Encrypt history:
// Global encryption:
i, err := inertia.New(
/* ... */
inertia.WithEncryptHistory(),
)
// Pre-request encryption:
ctx := inertia.SetEncryptHistory(r.Context())
// pass it to the next middleware or inertia.Render function using r.WithContext(ctx).Clear history:
ctx := inertia.ClearHistory(r.Context())
// pass it to the next middleware or inertia.Render function using r.WithContext(ctx).Built-in Vite integration that automatically detects hot reload vs bundled mode. By default, Vite integration assumes a standard public/ directory structure for assets, but it can be overwritten.
package main
import (
"log"
"net/http"
inertia "github.com/romsar/gonertia/v2"
)
func main() {
// First create your Inertia instance (you can use any inertia.New* method)
i, err := inertia.NewFromFile("resources/views/app.html")
if err != nil {
log.Fatal(err)
}
// Then wrap it with Vite functionality
app, err := inertia.NewWithVite(i)
if err != nil {
log.Fatal(err)
}
// The rest of your application setup...
mux := http.NewServeMux()
mux.Handle("/", app.Middleware(homeHandler(app)))
}All Vite integration settings can be customized:
// Create Inertia instance with any options you need
i, err := inertia.NewFromFile("resources/views/app.html",
inertia.WithSSR("http://localhost:13714"),
)
if err != nil {
log.Fatal(err)
}
// Wrap with Vite and configure Vite-specific options
app, err := inertia.NewWithVite(i,
inertia.WithHotFile("custom/hot"), // Hot reload file path
inertia.WithBuildManifest("public/build/manifest.json"), // Build manifest path
inertia.WithFallbackManifest("public/.vite/manifest.json"), // Fallback manifest
inertia.WithBuildDir("/assets/"), // Build output directory
inertia.WithHotReloadPort("//localhost:3000"), // Hot reload server port
)
if err != nil {
log.Fatal(err)
}Create your root template with Vite functions:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{{ .inertiaHead }}
<!-- Vite Refresh - automatically handles HMR setup for React/Preact/Vue -->
{{ viteRefresh }}
<!-- Or use framework-specific helpers: -->
<!-- {{ viteReactRefresh }} - React-specific HMR with refresh runtime -->
<!-- CSS - automatically resolves dev vs production -->
<link rel="stylesheet" href="{{ vite "resources/css/app.css" }}">
</head>
<body>
{{ .inertia }}
<!-- Main app script - automatically resolves dev vs production -->
<script type="module" src="{{ vite "resources/js/app.jsx" }}"></script>
</body>
</html>Automatic asset loading with configurable preload strategies:
app, err := inertia.NewVite(i,
inertia.WithEntryPoints("resources/js/app.tsx"),
inertia.WithWaterfallPreload(3),
)Template usage - Two approaches:
Option 1: Config-based
<head>
{{ .inertiaHead }}
{{ viteAssets }}
</head>Option 2: Template arguments
<head>
{{ .inertiaHead }}
{{ viteAssets "resources/js/app.tsx" }}
{{ viteAssets "app.js" "admin.js" }}
</head>Configuration options:
WithEntryPoints(...)- Specify entry points (required unless using template args)WithIntegrity()- Enable SubResource Integrity (requires Vite plugin like vite-plugin-manifest-sri)
Preload strategies:
WithoutPreloading()- Minimal output, browser handles discovery (default)WithAggressivePreload()- Preload all dependencies immediatelyWithWaterfallPreload(concurrent)- Batched prefetch with concurrency control
SubResource Integrity (SRI):
SRI hashes are automatically included in generated tags when present in the manifest. To add SRI support to your Vite build:
- Install vite-plugin-manifest-sri
- Add the plugin to your
vite.config.js - The
integrityfield will be read from the manifest and added to all asset tags
handler := app.CSPMiddleware()(app.Middleware(mux))Template:
{{ viteAssetsWithNonce .csp_nonce "app.tsx" }}Customize:
app.CSPMiddleware(
inertia.WithCSPPolicy("script-src 'nonce-{{nonce}}'"),
inertia.WithCSPNonceGenerator(customFunc),
)Returns func(http.Handler) http.Handler. Nonces applied to all tags. Merges with existing CSP headers.
The Vite integration provides the following template functions:
{{ viteAssets "entry.js" ... }}- Outputs all required assets (accepts optional entry point args){{ viteAssetsWithNonce .csp_nonce "entry.js" ... }}- Outputs assets with CSP nonce for enhanced security{{ vite "path" }}- Resolves asset URLs (dev vs production){{ viteRefresh }}- HMR setup for frameworks like Preact, Vue{{ viteReactRefresh }}- React-specific HMR with refresh runtime
Of course, this package provides convenient interfaces for testing!
func TestHomepage(t *testing.T) {
body := ... // get an HTML or JSON using httptest package or real HTTP request.
// ...
assertable := inertia.AssertFromReader(t, body) // from io.Reader body
// OR
assertable := inertia.AssertFromBytes(t, body) // from []byte body
// OR
assertable := inertia.AssertFromString(t, body) // from string body
// now you can do assertions using assertable.Assert[...] methods:
assertable.AssertComponent("Foo/Bar")
assertable.AssertVersion("foo bar")
assertable.AssertURL("https://example.com")
assertable.AssertProps(inertia.Props{"foo": "bar"})
assertable.AssertEncryptHistory(true)
assertable.AssertClearHistory(true)
assertable.AssertDeferredProps(map[string][]string{"default": []string{"foo bar"}})
assertable.AssertMergeProps([]string{"foo"})
// or work with the data yourself:
assertable.Component // Foo/Bar
assertable.Version // foo bar
assertable.URL // https://example.com
assertable.Props // inertia.Props{"foo": "bar"}
assertable.EncryptHistory // true
assertable.ClearHistory // false
assertable.MergeProps // []string{"foo"}
assertable.Body // full response body
}Also, you can check one more golang adapter called petaki/inertia-go.
Full list of community adapters is located on inertiajs.com.
This package is based on inertiajs/inertia-laravel and uses some ideas of petaki/inertia-go.
Gonertia is released under the MIT License.
