nexus

package module
v2.33.7 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: MIT Imports: 74 Imported by: 0

README

nexus

One Go function. Every transport.
REST, GraphQL and WebSocket from one signature, plus DI, an embedded Vite frontend and a live dashboard.

Docs Go Reference Version Go version

Get started · Why nexus · CLI · Examples · Changelog


nexus is a Go framework. You write a plain function with typed input and output. nexus serves it over REST, GraphQL and WebSocket, injects its dependencies, and shows it on a live dashboard at /__nexus. There are no schema files and no codegen step to run, and you deploy one binary with the frontend included.

type Greeter struct{}

func NewGreeter() *Greeter { return &Greeter{} }

type HelloArgs struct {
    Name string `json:"name" graphql:"name,required"`
}

func (g *Greeter) SayHello(ctx context.Context, in HelloArgs) (string, error) {
    return "Hello, " + in.Name + "!", nil
}

func main() {
    nexus.Boot(nexus.Module("hello",
        nexus.Provide(NewGreeter),
        nexus.AsQuery((*Greeter).SayHello),                  // GraphQL
        nexus.AsRest("POST", "/hello", (*Greeter).SayHello), // REST
    ))
}
curl localhost:8080/graphql -H 'content-type: application/json' -d '{"query":"{ sayHello(name:\"world\") }"}'
curl localhost:8080/hello   -H 'content-type: application/json' -d '{"name":"world"}'

Quick start

go install github.com/paulmanoni/nexus/cmd/nexus/v2@latest
# or, pinned in a project's go.mod: go get -tool github.com/paulmanoni/nexus/cmd/nexus/v2@latest
#                                   go tool nexus dev

nexus new my-app      # --frontend vue|react, --inertia, --db, --auth …
cd my-app && go mod tidy
nexus dev             # live reload; dashboard at http://localhost:8080/__nexus

You need Go 1.26+. The build is pure Go, with no CGO. A frontend also needs Node.js 20+, but only at development and build time: the binary you ship runs without it.

What's inside

The architecture dashboard

Documentation

Guides and reference live at paulmanoni.github.io/nexus. The CLI also carries a quick reference for each feature, matched to its version: run nexus docs --list or nexus docs handlers.

The site's source is in docs/, built with VitePress. To run it locally: cd docs && npm install && npm run dev.

License

MIT

Documentation

Overview

Package nexus is a thin framework over a pluggable HTTP router (stdlib by default; gin/chi opt-in) that registers every endpoint (REST, GraphQL, WebSocket) into a central registry, traces every request into an in-memory event bus, and exposes both under /__nexus for tooling — notably the Vue dashboard.

GraphQL schemas are derived from handlers registered with AsQuery and AsMutation; the engine executing them is internal (the gql package holds the types handlers and middleware see).

Entry points

An app starts with exactly one of three verbs — pick by where Config comes from:

  • Boot(opts...) — the default. Loads nexus.toml (runtime Config, every [extensions.*] block, the [env] bridge, the config.Get store), then runs. Use BootFrom(path, opts...) for an explicit config path. This is what scaffolded apps use; settings live in the file, not in code.
  • Run(cfg, opts...) — when you build Config in Go (a shared Store value, a middleware func slice, a pluggable backend — things TOML can't express). Boot is sugar over Run.
  • InProcess(cfg, opts...) — for tests. Boots with every route mounted but no network listener; the returned *App is an http.Handler. The nexustest package wraps this.

Everything else is a building block Boot composes for you and you rarely call directly: New(cfg) (construct an *App without running), config.Load / config.MustLoad (read config.Runtime from TOML), and LoadExtensionOptions / MustLoadExtensions (read [extensions.*] options from TOML).

Index

Constants

View Source
const (
	DefaultShutdownTimeout = 10 * time.Second
	DevShutdownTimeout     = 250 * time.Millisecond
)

Shutdown windows applied when Config.Server.ShutdownTimeout is zero.

Production gets a real drain so in-flight requests finish before the process exits. Dev gets almost none: `nexus dev` replaces the process on every save, nothing in flight is worth preserving, and every millisecond spent here is a millisecond of Ctrl-C the developer sits through.

View Source
const AuthFlowTag = "auth.flow"

AuthFlowTag is the registry.Endpoint.Tags key used by AuthRoute to mark which framework auth flow ("login" | "logout" | "me") an endpoint belongs to. The client SDK reads this tag to expose top-level auth.login() / auth.logout() / auth.me() calls so users don't have to know the underlying route shape — the framework surfaces it via convention without owning the handlers themselves.

View Source
const DefaultGraphQLPath = "/graphql"

DefaultGraphQLPath is the mount path nexus.AsQuery / AsMutation use when a service hasn't called AtGraphQL.

View Source
const DefaultIdleTimeout = 120 * time.Second

DefaultIdleTimeout caps idle keep-alive connections. Go's own default is "fall back to ReadTimeout", and with ReadTimeout unset that means never — so an unauthenticated client can park connections until the process runs out of file descriptors.

View Source
const DefaultManifestPath = "nexus.toml"

DefaultManifestPath is the file the framework auto-loads from the current working directory at boot. Operators who need a different path call `app.LoadDeployManifest("alt-path.toml")` from their own nexus.Invoke — that runs AFTER auto-load and the framework's declarations are idempotent (last writer wins on each block) so explicit overrides land cleanly.

View Source
const DefaultMaxBodyBytes = 32 << 20

DefaultMaxBodyBytes is the request-body cap when the operator sets none.

View Source
const EnvAdminToken = "NEXUS_ADMIN_TOKEN" // #nosec G101 -- env var name, not a credential value

EnvAdminToken is the env var the framework reads for the admin token gating GET /__nexus/manifest. Empty value (or unset) leaves the endpoint unmounted — fail-closed so a forgotten orchestrator config doesn't expose declared services / env / crons.

View Source
const GlobalErrorKey = "_global"

GlobalErrorKey is the reserved field name Error.Global writes under. It is part of the wire contract: Inertia clients read page.props.errors._global, REST clients find it inside the 422 body's errors map, GraphQL clients in the error's extensions.

View Source
const PublicTag = "auth.public"

PublicTag is the registry.Endpoint.Tags key set by Public(). When an extension installs a default endpoint gate (deny-by-default auth), endpoints carrying this tag are exempted from it.

Variables

View Source
var ErrNoFrontendDocument = errors.New("nexus: no frontend index.html to render into")

ErrNoFrontendDocument means there is no index.html to render into right now: no frontend is registered, the build is module-only (nexus({ input: 'src/main.ts' }) emits no index.html), nothing is built yet (the placeholder page is not a document), or the live Vite dev server did not serve its index.html. Module-only is decided the same way in development as in production: a live dev server whose hot file declares no HTML entry stands for a module-only build, so this is returned even if that server's root holds an index.html. A page renderer then builds its own document.

Functions

func ActiveEnvironment

func ActiveEnvironment() string

ActiveEnvironment is the environment the process is booting into, for code with no *App at hand (a resource's logger, an extension's init): NEXUS_ENVIRONMENT when set, else runtime environment from the loaded nexus.toml — the same rule App.Environment applies, so the two agree for an app configured from the file.

func Boot

func Boot(opts ...Option)

Boot loads nexus.toml automatically — the runtime Config, every [extensions.*] block, the [env] bridge, and the config.Get base layer — then runs the app. It's the zero-boilerplate form of:

cfg  := config.MustLoad()
ext := nexus.MustLoadExtensions()
nexus.Run(cfg, append(opts, userOpts...)...)

so main() collapses to:

func main() {
    nexus.Boot(
        nexus.Frontend(webFS, "web/dist"),
        billing.Module,
    )
}

A missing nexus.toml is tolerated (zero Config, no extensions) so apps without one still boot; a malformed one panics, matching the MustLoad* helpers. Override the path with the NEXUS_CONFIG env var, or call BootFrom(path, opts...).

Run stays available for apps that build Config in Go or want explicit control over load order — Boot is sugar over it. Note that extension PACKAGES still need their blank import (Go links only imported code); Boot removes the load calls, not the imports.

func BootFrom

func BootFrom(path string, opts ...Option)

BootFrom is Boot with an explicit nexus.toml path.

func CheckConnection added in v2.4.0

func CheckConnection(ctx context.Context) error

CheckConnection runs the registered ConnectionChecks; the first error wins. Transports with their own sockets (view's live pages) call it per message.

func ClientIP

func ClientIP(ctx context.Context) string

ClientIP is the caller's address for the request ctx belongs to — on every transport, and honouring [runtime.server] trusted_proxies, so a forwarded client is reported only behind a proxy you trust.

func RegisterBootCheck

func RegisterBootCheck(fn BootCheck)

RegisterBootCheck adds a boot-time self-check. Call it from an init() in the package that owns the invariant — the same pay-for-what-you-use pattern as dashboard.RegisterSnapshotExtra: the check only exists if the app imports that package, so the framework core stays free of the dependency. Safe to call before Run.

func RegisterBuiltinOptions added in v2.27.2

func RegisterBuiltinOptions(fn func() []Option)

RegisterBuiltinOptions registers a source of Options a framework package contributes whenever it is linked — the view runtime's scripts, a component kit's assets. Unlike RegisterDeferredOptions, DecoratedModules never drops them: a boot scoped to some annotated modules still serves the runtime its pages load.

Intended for framework packages; apps don't call it.

func RegisterConnectionCheck added in v2.4.0

func RegisterConnectionCheck(fn ConnectionCheck)

RegisterConnectionCheck adds a ConnectionCheck. Safe to call from package init.

func RegisterDeferredOptions

func RegisterDeferredOptions(fn func() []Option)

RegisterDeferredOptions registers a source of Options collected at Boot/Run time. Sources run in registration order, inserted after the app's own options and before the GraphQL auto-mount, so decorator-registered endpoints participate in schema assembly exactly like hand-written ones.

Intended for framework integration (nexus/decorate); apps don't call it.

func RegisterExtensionDecoder

func RegisterExtensionDecoder(name string, dec ExtensionDecoder)

RegisterExtensionDecoder makes name a recognized [extensions.<name>] block in nexus.toml. The decoder gets the raw TOML bytes of just that sub-tree.

Idiomatic usage: each extension's init() registers itself:

package myext

func init() {
    nexus.RegisterExtensionDecoder("myext", decode)
}

func decode(raw []byte) ([]nexus.Option, error) {
    var c MyExtConfig
    if err := toml.Unmarshal(raw, &c); err != nil { return nil, err }
    return []nexus.Option{Plugin(c)}, nil
}

Calling RegisterExtensionDecoder twice with the same name replaces the prior decoder — operators with conflicting extension imports get the LAST registration, which is usually what they want when testing with a stub.

Names are case-sensitive. Convention is lowercase kebab (`"myext"`, `"oauth2"`, `"rate-limit"`) matching the TOML idiom; the framework doesn't enforce this.

func RegisterGqlType

func RegisterGqlType[T any](name string, values ...T)

RegisterGqlType declares Go type T as the GraphQL input type name, which an args field opts into with a `graphql:"field,type=Name"` tag.

With values, T must be a string or integer type and becomes an enum whose members are the values (each member is named fmt.Sprint(v), and binds back to v):

type Status string
nexus.RegisterGqlType("Status", Status("active"), Status("archived"))

type ListArgs struct {
    Status Status `graphql:"status,type=Status"`
}

Without values, T must be a struct and becomes an input object named name, its fields mapped like an args struct's; every argument of type T then uses that name. Call it once, before the app boots (from an init or main); re-registering a name replaces the earlier type. It panics when T can't be represented.

func RegisterIdentityRestorer added in v2.7.0

func RegisterIdentityRestorer(fn IdentityRestorer)

RegisterIdentityRestorer adds an IdentityRestorer. Safe from package init.

func RegisterRequestIdentity

func RegisterRequestIdentity(fn RequestIdentityFunc)

RegisterRequestIdentity adds a source of request identity. WebSocket endpoints (AsWS) use it to know which user a connection belongs to, which is what EmitToUser addresses — so it must read what the server authenticated (the request context an auth middleware populated), never anything the client sent. The first registered source that reports an id wins. Safe to call from package init.

func RegisterRequestImpersonator added in v2.11.0

func RegisterRequestImpersonator(fn RequestImpersonatorFunc)

RegisterRequestImpersonator adds a source of the real user behind an impersonated request; extension/auth registers one. Safe from package init.

func RegisterSharedPageProp added in v2.3.0

func RegisterSharedPageProp(fn SharedPagePropFunc)

RegisterSharedPageProp adds a prop every page renderer (extension/inertia) shares with every page, before the app's own shared props — so an app's prop of the same key wins. extension/auth shares "auth" this way. Safe to call from package init.

func RegisterWSCarrier

func RegisterWSCarrier(fn WSCarrier)

RegisterWSCarrier adds a WSCarrier. Copy only values that may outlive the request: the upgrade request's context also holds per-request state (a Scoped memo, a session handle) that must not be shared by every message of a long-lived connection. Values are captured once, at the upgrade — a connection keeps the identity it was opened with. Safe to call from package init.

func RegisteredExtensionNames

func RegisteredExtensionNames() []string

RegisteredExtensionNames returns the sorted list of every extension name a decoder is registered for. Useful for lint + diagnostic output ("declared: [a, b]; available: [a, b, c]").

func RequestIdentity

func RequestIdentity(ctx context.Context) (id string, ok bool)

RequestIdentity reports the authenticated subject of a request, as the registered identity sources (extension/auth, or the app's own) see it. It is what extensions record as "who did this" — the enqueuer of a background job, for instance.

func RequestImpersonator added in v2.11.0

func RequestImpersonator(ctx context.Context) (string, bool)

RequestImpersonator reports the real user behind a request that acts as RequestIdentity's user — what extensions record beside it (a job's Impersonator). False when the request isn't an impersonation.

func RequestParam added in v2.11.0

func RequestParam[T any](fill func(ctx context.Context) (T, error))

RequestParam lets every handler — REST, GraphQL, WebSocket, pages — declare a parameter of type T, filled from the request's context on each call; an error answers the request instead of calling the handler. extension/auth registers *auth.Identity (the caller, nil when anonymous) and auth.Identity (the caller, or Unauthenticated). Call it from package init, before handlers are registered.

func RestoreIdentity added in v2.7.0

func RestoreIdentity(ctx context.Context, app *App, id string) (context.Context, error)

RestoreIdentity runs the registered IdentityRestorers over ctx for user id; extension/jobs calls it before running a job someone enqueued. An error (the account is gone) means the work must not run as them.

func Reverse added in v2.22.0

func Reverse(ctx context.Context, name string, params ...any) (string, error)

Reverse is URL with the error returned.

func RoutePrefix

func RoutePrefix(p string) routePrefixOption

RoutePrefix prepends a string to the paths of the REST endpoints it applies to. Two usage patterns:

// Module-wide: every AsRest in the module sees "/api/v1".
nexus.Module("orders", nexus.RoutePrefix("/api/v1"),
    nexus.AsRest("GET", "/orders", NewListOrders),  // → /api/v1/orders
    nexus.AsRest("POST", "/orders", NewCreateOrder),
)

// Per-endpoint:
nexus.AsRest("GET", "/health", NewHealth, nexus.RoutePrefix("/ops"))

The prefix is stored verbatim — include (or omit) the leading slash yourself; nexus does not normalize. Stacking within a single Module concatenates left-to-right, so `Module(..., RoutePrefix("/a"), RoutePrefix("/b"), AsRest("GET", "/x", ...))` mounts at /a/b/x. Prefixes do NOT stack across nested Module calls — the inner module already stamped its children before the outer sees them. If you need stacking, compose the prefix string explicitly.

func Run

func Run(cfg config.Runtime, opts ...Option)

Run starts an app from a Config you build in Go, plus the given options (modules, Provide, AsRest/AsQuery/AsWS, extension modules). It blocks until the process is signalled to stop.

Most apps should call Boot instead — it loads Config + [extensions.*] from nexus.toml and is sugar over Run. Reach for Run when Config carries values TOML can't express (a shared Store, a middleware func slice, a pluggable router/container backend) or when you want explicit control over load order. For tests, use InProcess (no listener). See the package doc for the full entry-point rundown.

func ServerTLSConfig

func ServerTLSConfig(certFile, keyFile, caFile string) (*tls.Config, error)

ServerTLSConfig builds a *tls.Config for a server-terminating Listener. certFile and keyFile are required (PEM-encoded server cert + key). caFile is optional: when set, the listener requires clients to present a certificate signed by that CA (mTLS), and 1.3 handshakes for clients without one will fail at the TLS layer before any HTTP request is dispatched. Pass "" to skip client auth.

Defaults: TLS 1.2 minimum (1.0/1.1 are deprecated and unsafe); modern cipher suite selection left to Go's defaults, which track the IETF recommended list.

cfg, err := nexus.ServerTLSConfig("admin.crt", "admin.key", "admin-ca.crt")
if err != nil { log.Fatal(err) }
listener := config.Listener{Addr: "10.0.0.5:9443", Scope: config.ScopeAdmin, TLS: cfg}

func SetGraphStatus

func SetGraphStatus(ctx context.Context, code int)

SetGraphStatus overrides the HTTP status code for the current GraphQL request. Call from a gql.Middleware (the Graph realization of a middleware.Middleware bundle) or from a resolver to translate a decision into a non-200 response code:

authMw := middleware.Middleware{
    Name: "auth",
    Graph: func(next gql.Resolver) gql.Resolver {
        return func(f gql.Field) (any, error) {
            if !authed(f.Context) {
                nexus.SetGraphStatus(f.Context, http.StatusUnauthorized)
                return nil, errors.New("unauthorized")
            }
            return next(f)
        }
    },
}

Without this call the framework returns 200 OK with errors in the GraphQL response body — the GraphQL-spec default. When called multiple times within one request, the LAST value wins.

No-op when ctx didn't pass through the framework's GraphQL adapter — useful for resolver code under test with a bare engine call.

The GraphQL transport is internal; this is its public status hook.

func URL added in v2.22.0

func URL(ctx context.Context, name string, params ...any) string

URL builds the URL of the route named name in the app serving ctx (see Route.Reverse for params). Like Route.URL it panics under nexus dev and in tests when the route can't be built, and logs and returns "#" otherwise.

func Validate

func Validate(v any) error

Validate checks v's `validate:` tags — the rules GraphQL arguments use (required, len=min|max, int=min|max, oneof=a|b|c) — and returns an InvalidInput *Error with every failing field's message, or nil. Nested structs are checked too, their fields keyed "parent.child".

Every transport runs it on a handler's bound args before the handler is called; call it directly for a value bound by hand (Form.Bind, a decoded payload).

func WithApp added in v2.22.0

func WithApp(ctx context.Context, app *App) context.Context

WithApp is ctx carrying app, so URL and Reverse build its routes — for code outside a request (a job, a test) in a process running several apps. A request's context carries its app already.

func WithScopedValue

func WithScopedValue[T any](ctx context.Context, s *Scoped[T], val T) context.Context

WithScopedValue pre-fills a handle's value on a context — the unit-test door, so a handler that reads a Scoped fact is testable without booting an app or touching the real compute. Copy-on-write: the returned context carries a fresh store layered over any existing one, so pre-filling never races a concurrent Get on the original.

func WriteError

func WriteError(c *httpx.Ctx, err error)

WriteError writes err as a REST error response — the status of its code and the {"code", "message", "errors"} body — and aborts the chain. For raw handlers (an *httpx.Ctx param) and extensions that answer a request themselves.

Types

type ActionAuthorizer

type ActionAuthorizer interface {
	Authorize(ctx context.Context, action string) error
}

ActionAuthorizer is implemented by a controller that authorizes each action itself — the typed, explicit form of a before-action hook:

func (c *UsersController) Authorize(ctx context.Context, action string) error {
    if action == "Destroy" && !auth.Can(ctx, "users:delete") {
        return errors.New("you cannot delete users")
    }
    return nil
}

It runs after the router's gates (so the identity is resolved) and before the action. A non-nil error ends the request through the action's normal error path as nexus.Forbidden with the error's message — a REST 403, a GraphQL FORBIDDEN, the Inertia ErrorPage — unless it already carries a code (nexus.Err(nexus.NotFound, …) stays a 404; nexus.Invalid() stays a validation response).

type App

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

func InProcess

func InProcess(cfg config.Runtime, opts ...Option) (app *App, stop func(context.Context) error, err error)

InProcess assembles and starts an App exactly like Run — same early/user/late option ordering, so AsRest/AsQuery/AsMutation/AsWS are fully mounted and every user middleware is installed — but it does NOT bind a network listener. The returned *App is an http.Handler (App.ServeHTTP), so tests can drive real routing through httptest without a socket. Call stop to run lifecycle teardown (resource Close, worker cancel, etc.).

This is the supported building block for the nexustest package and for any app that wants to exercise its own handlers in-process. Production code uses Boot/Run; InProcess exists for tests.

func New

func New(cfg config.Runtime) *App

New constructs an *App from a single Config. The canonical (and, since v0.18, only) public constructor — both nexus.Run and the lower-level "build app, then app.Run(addr)" pattern feed through here.

Behavior:

  • Manifest-derived defaults (codegen'd by `nexus build --deployment X`) fill any zero Config field; explicit Config fields always win.
  • The framework owns engine creation, scope-filter middleware, /__nexus/health + /ready, the cache + ratelimit + metrics stores, and (when EnableDashboard is true) the dashboard mount.
  • Listeners with empty Addrs auto-fill from the resolved Config.Addr (admin = port+1000, internal = port+2000).
  • Global rate limit and global middlewares are installed at the engine root in registration order.

The returned *App is fully constructed and safe to register endpoints/services on, but listeners aren't bound until Run is invoked (either nexus.Run or App.Run for direct callers).

func (*App) AddStartupTask

func (a *App) AddStartupTask(t manifest.StartupTask)

AddStartupTask registers a one-shot task that runs before listeners bind. Migrations and other pre-start side-effecting work belong here. The Run function is opaque to print mode (manifest only surfaces Name + Description + Phase), so a print-mode invocation never actually executes Run — it just lists the task so the orchestration platform knows one is expected.

The Run function IS executed in normal boot mode, sequenced by runStartupTasks at the head of the lifecycle OnStart hook. Failure halts boot with the task name surfaced in the error.

func (*App) AllowIntrospection

func (a *App) AllowIntrospection(c *httpx.Ctx) bool

AllowIntrospection reports whether the request c is permitted to see schema-shape data — drives both the dashboard gate and the GraphQL adapter's __schema-query block. Returns true when Config.Introspection is true OR the TCP peer falls within Config.IntrospectionNetworks. Exposed so transport adapters outside the nexus package (notably gql) can consult one source of truth.

func (*App) Bus

func (a *App) Bus() *trace.Bus

func (*App) Cache

func (a *App) Cache() resource.Cache

func (*App) ClientContributors

func (a *App) ClientContributors() []ClientContributorRecord

ClientContributors returns a snapshot of every registered codegen contributor. Order matches registration order; the returned slice is a copy so callers can iterate without holding the lock.

func (*App) ClientHandler

func (a *App) ClientHandler() *client.Handler

ClientHandler returns the live *client.Handler when the client SDK is mounted (Config.Client.Enabled OR a nexus.ClientUse option fired in the chain), nil otherwise. Used by auth.Module's option chain to wire the AuthInfo bridge without forcing app code to thread the manager through Mount manually.

func (*App) Cron

func (a *App) Cron(name, schedule string) *CronBuilder

Cron starts building a scheduled job. Finalize with .Handler(fn). Jobs run bare — middleware chains do not apply — but the scheduler still emits request.start / request.end trace events so they appear on the dashboard Traces tab.

app.Cron("refresh-pets", "*/5 * * * *").
    Describe("Warm the pet cache").
    Handler(func(ctx context.Context) error { return nil })

func (*App) DeclareCORS

func (a *App) DeclareCORS(c manifest.CORSBlock)

DeclareCORS sets the cross-origin policy block read by the extension/cors plugin at boot. Idempotent — last call wins.

func (*App) DeclareEnv

func (a *App) DeclareEnv(e manifest.EnvVar)

DeclareEnv records one env var the app reads. Safe to call from any di.Invoke — typically from a module-level nexus.DeclareEnv option, which expands to an invoke that calls this. Empty Name is silently dropped to keep callers from having to guard zero values when they build env lists from a slice.

func (*App) DeclareEnvProvider

func (a *App) DeclareEnvProvider(p manifest.EnvProvider)

DeclareEnvProvider records a provider whose NexusEnv() is called at manifest assembly time. Use when a module's env list is data-driven (e.g. one EnvVar per registered DB connection); use DeclareEnv directly when the list is static.

func (*App) DeclareEnvironment

func (a *App) DeclareEnvironment(e manifest.Environment)

DeclareEnvironment records a deploy target ("production", "staging", "preview", ...). The orchestration platform consults the list to know which environments the binary is built for; the active one (Config.Environment / NEXUS_ENVIRONMENT) is matched against this set at boot.

func (*App) DeclareErrors

func (a *App) DeclareErrors(e manifest.ErrorsBlock)

DeclareErrors sets the error-capture configuration block read by the extension/errors plugin at boot. Idempotent — last call wins.

func (*App) DeclareFile

func (a *App) DeclareFile(f manifest.File)

DeclareFile records a mounted-blob input — TLS bundle, JSON config override, etc. The platform writes the bytes to Path at deploy time. Empty Name or Path is silently dropped.

func (*App) DeclareHooks

func (a *App) DeclareHooks(h manifest.Hooks)

DeclareHooks sets the platform-orchestrated build/predeploy/ postdeploy commands. Idempotent within a single boot: subsequent calls fully replace the previous Hooks block (rather than accumulating) — typical use is one call from the top-level main() with the full set.

func (*App) DeclareOverride

func (a *App) DeclareOverride(env string, ov manifest.Override)

DeclareOverride registers a per-environment Override against the declared inputs. env must match a previously-declared Environment; validation happens at merge time via manifest.MergeOverrides, not here, so the declaration order doesn't matter.

Calling DeclareOverride twice for the same env REPLACES the previous diff — there's no merging at registration time. This matches operator intent: one module owns the prod override for a given env, not a chain of modules each contributing slices.

func (*App) DeclareSecret

func (a *App) DeclareSecret(s manifest.Secret)

DeclareSecret records one sensitive input the app reads. Distinct from DeclareEnv so the platform's secret store can manage it separately (encrypted at rest, redacted in UI, rotation reminders). Empty Name is silently dropped.

func (*App) DeclareService

func (a *App) DeclareService(s manifest.ServiceNeed)

DeclareService records a backing-service dependency (Postgres, Redis, RabbitMQ, etc.) the orchestration platform should provision and bind. The ExposeAs map drives env-var fill-in: when the platform binds the sidecar, it sets each named env var to the corresponding field of the resolved sidecar.

func (*App) DeclareServiceProvider

func (a *App) DeclareServiceProvider(p manifest.ServiceDependencyProvider)

DeclareServiceProvider is the data-driven counterpart to DeclareService.

func (*App) DeclareTLS

func (a *App) DeclareTLS(t manifest.TLSBlock)

DeclareTLS sets the public-internet TLS configuration block read by the extension/tls plugin at boot. Idempotent within a single boot: subsequent calls fully replace the previous block.

func (*App) DeclareVolume

func (a *App) DeclareVolume(v manifest.Volume)

DeclareVolume records a writable path that must persist across restarts. The orchestration platform mounts a persistent volume at each declared path. Set Shared=true when the path must be visible to every replica (e.g. uploads dir read by all instances) — single- replica apps can leave it false.

func (*App) DeclareVolumeProvider

func (a *App) DeclareVolumeProvider(p manifest.VolumeProvider)

DeclareVolumeProvider is the data-driven counterpart to DeclareVolume.

func (*App) EffectiveManifest

func (a *App) EffectiveManifest() *manifest.Manifest

EffectiveManifest returns the merged + validated manifest produced at boot. Returns nil before fx.Start completes — callers serving /__nexus/manifest fall back to manifest.Build(manifestInputs()) so print mode and pre-boot inspection still work.

func (*App) Environment

func (a *App) Environment() string

Environment returns the resolved environment name ("production", "staging", "preview", ...) the binary is booting into: NEXUS_ENVIRONMENT when set, else Config.Environment (nexus.toml's runtime environment). Empty when neither is set.

func (*App) ExemptCSRF added in v2.5.0

func (a *App) ExemptCSRF(path string)

ExemptCSRF exempts one path (as registered; the route prefix is added) from the CSRF check — or, ending in "/*", every path under it. Only for endpoints a cross-site post can't abuse: ones that set no cookie and answer only to the caller, such as an OAuth2 token endpoint or an API for devices that sign in with tokens.

func (*App) FrontendDocument

func (a *App) FrontendDocument(ctx context.Context) (FrontendDocument, error)

FrontendDocument returns the document pages render into, or ErrNoFrontendDocument. Any other error means a hot file is present but can't be understood — malformed, an unknown schema version, an invalid origin — and should be shown to the developer rather than papered over. A hot file left by a dev server that has exited is not an error: it reads as absent, and the built index.html (or ErrNoFrontendDocument) is returned.

func (*App) FrontendFS

func (a *App) FrontendFS() (fsys fs.FS, root string, ok bool)

FrontendFS returns the built frontend bundle registered by Frontend — the embed.FS and the dist root within it — and whether one was registered. An extension that needs to READ the bundle (e.g. inertia.Module resolving the Vite manifest) calls this instead of having the bundle passed to it again, so the app declares its frontend in exactly one place.

func (*App) FrontendMount

func (a *App) FrontendMount() string

FrontendMount is the URL path Frontend serves the bundle under — the route prefix plus FrontendAt — or "" at the site root. A file at "assets/x.js" in the bundle is served at FrontendMount()+"/assets/x.js", which is what a renderer must link to rather than assuming "/".

func (*App) LoadDeployManifest

func (a *App) LoadDeployManifest(path string) error

LoadDeployManifest reads nexus.toml at path, parses its inputs surface (environments / secrets / files / hooks / environment_overrides), and registers each entry through the existing Declare* methods. Idempotent: re-declaring an environment with the same name is a no-op, secrets / files dedup by name, and DeclareOverride replaces any prior diff for the same environment.

Intended call sites:

  • Directly in main() before nexus.Run, when the operator wants YAML to be the source of truth for the inputs surface.
  • From a nexus.Invoke(...) for apps that want the inputs to participate in fx ordering.
  • From a codegen'd init() emitted by `nexus build` (future extension — the codegen path that currently bakes deployment defaults will also bake DeclareEnvironment / DeclareSecret / DeclareOverride calls so the runtime stays file-IO-free).

YAML parse errors return immediately. Schema validation (duplicate names, malformed validation rules) is NOT performed here — call manifest.Lint() on the result manifest to surface those issues. Boot validation against actual env values still runs at di.Start via resolveEffectiveManifest.

Missing file is treated as an error so a typo in the path doesn't silently produce an empty inputs surface. To make the call optional, stat the file first or wrap in a guard.

func (*App) Logger

func (a *App) Logger() *slog.Logger

Logger returns the app's structured logger. It is also what the framework provides into the DI graph as *slog.Logger, so binders (db, cache, Managed, …) and any constructor that takes a *slog.Logger share it.

The default writes JSON to stdout (slog.NewJSONHandler, AddSource on) at the level in [runtime.logging] level (debug | info | warn | error; info when unset). `nexus dev` renders those lines in its columnar log view; a production binary emits them as-is for a log collector. Replace it with WithLogger.

func (*App) Metrics

func (a *App) Metrics() metrics.Store

func (*App) OnResourceUse

func (a *App) OnResourceUse(target UseReporter)

OnResourceUse installs an auto-attach hook onto any UseReporter (typically a registry of named instances). Whenever code calls target.UsingCtx(ctx, "resource-name") during a request, the hook:

  1. reads the current trace.Span from ctx so we know which service made the call
  2. AttachResource(service, resource) on the registry — edge appears live
  3. emits a "downstream" trace event so the Traces tab shows the lookup

Calls with no span in context (e.g. UsingCtx fired from main or a cron job outside the trace middleware) are silently ignored — there's no service to attribute the usage to.

func (*App) Plugins

func (a *App) Plugins() []PluginRecord

Plugins returns a snapshot of every registered plugin. Order matches registration order; the returned slice is a copy, safe to mutate.

func (*App) PrefixPath

func (a *App) PrefixPath(p string) string

PrefixPath returns p with the deployment route prefix prepended. Mount sites use this so a single binary can be served behind a path-based ingress without each registration re-implementing the prepend. Both inputs are expected to start with "/"; the helper is a noop when the prefix is empty.

func (*App) Register

func (a *App) Register(r resource.Resource)

Register adds a resource (database, cache, queue) to the app so its health shows up on the dashboard. Use Service.Attach(r) to also draw an edge between the owning service(s) and the resource.

func (*App) RegisterClientContributor

func (a *App) RegisterClientContributor(rec ClientContributorRecord)

RegisterClientContributor records a per-plugin codegen contribution. Called by extension.Use when a Plugin declares a Contributor slot. Many contributors may be registered (one per plugin); the contributions route invokes them in registration order. Duplicate plugin names are allowed (re-registration appends — useful in tests; both copies run, which matches "last write wins" for files sharing a Path once the CLI merges them).

func (*App) RegisterIsland

func (a *App) RegisterIsland(name string, t reflect.Type)

RegisterSharedProp records the value type of a page-wide shared prop (an Inertia prop every page receives) so the client SDK can type it: t is walked into the same named-type pool endpoint schemas use — a named struct lands once in the manifest's refs — and the result is stored in the registry under key. The manifest projects the set as sharedProps and the generator emits it as NexusSharedProps. inertia.ShareScoped and inertia.ShareTyped call this; untyped providers (inertia.Share) are not recorded and ride NexusSharedProps' index signature.

A nil t or empty key is ignored. Call during option wiring (an Invoke); the manifest is built after boot. RegisterIsland records a view island's props type (view.NewIsland does it at boot), so the client SDK types it as NexusIslandProps[name].

func (*App) RegisterPlugin

func (a *App) RegisterPlugin(rec PluginRecord)

RegisterPlugin records plugin metadata on the app. Called by extension.Use during fx.Start. Duplicate Names overwrite — the last registration wins so test harnesses can re-wire plugins in place.

func (*App) RegisterSharedProp

func (a *App) RegisterSharedProp(key string, t reflect.Type)

func (*App) Registry

func (a *App) Registry() *registry.Registry

func (*App) ReportPeerHealth

func (a *App) ReportPeerHealth(tag string, ready bool, lastErr string)

ReportPeerHealth records one peer's probe outcome for the /__nexus/ready readiness gate. extension/peer's prober calls this on every probe round; anything else that tracks a hard downstream dependency may too. A peer reported not-ready flips /__nexus/ready to 503 until a later report clears it.

func (*App) RequireCSRF

func (a *App) RequireCSRF(reason string)

RequireCSRF records that something the app uses — cookie sessions, an auth scheme reading a cookie, Inertia or server-rendered forms — needs CSRF protection. Extensions call it from their module; unless the config forces CSRF off, the double-submit check is then installed once every option has run.

func (*App) RoutePrefix

func (a *App) RoutePrefix() string

RoutePrefix returns the deployment-wide path prefix applied to every user-mounted route (REST, GraphQL, WebSocket). Empty when no manifest `prefix:` (or Config.Server.RoutePrefix) was set.

func (*App) Router

func (a *App) Router() httpx.Router

Router returns the app's live HTTP router as the transport-neutral httpx.Router — the backend chosen by nexus.WithRouter (stdlib by default; gin/chi opt-in). Low-level handlers and extensions mount routes and middleware through this seam, never against a concrete engine type.

func (*App) Routes added in v2.22.0

func (a *App) Routes() []RouteInfo

Routes lists the app's named routes, sorted by name.

func (*App) Run

func (a *App) Run(addr string) error

func (*App) Scheduler

func (a *App) Scheduler() *cron.Scheduler

func (*App) SchemaRefs

func (a *App) SchemaRefs() map[string]registry.NamedType

SchemaRefs is the public accessor for the deduped named-type pool. Used by the client SDK package (client/) at manifest-build time to populate the Refs section. Returns the live map; callers MUST NOT mutate.

func (*App) ServeHTTP

func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*App) Service

func (a *App) Service(name string) *Service

func (*App) SetClientAuthInfo

func (a *App) SetClientAuthInfo(fn func() client.ExtractorInfo)

SetClientAuthInfo installs the manifest's auth-section provider on the mounted SDK handler. No-op when the client SDK isn't mounted (apps that don't ship the SDK pay nothing). Designed for auth.Module's option chain to call via fx.Invoke once both auth.Manager and the SDK are in scope.

func (*App) SetClientAuthMeta

func (a *App) SetClientAuthMeta(meta client.AuthMeta)

SetClientAuthMeta overlays the auth-config hints (login-token location + CSRF cookie/header names) onto the SDK manifest's Auth section. No-op when the SDK isn't mounted. Called by auth.Module's client bridge alongside SetClientAuthInfo.

func (*App) SetRequestValue added in v2.21.0

func (a *App) SetRequestValue(key, val any)

SetRequestValue has every request the app serves carry val under key in its context (context.Value), on every transport: how a package used by several apps in one process tells, from a request's context, which app is serving it. A second call with the same key replaces the value.

func (*App) SetValue

func (a *App) SetValue(key, value any)

SetValue stashes a key/value on the app. Extensions use it to record boot-time state (typically in an fx.Invoke) that they must read back at request time — without depending on gin-middleware install ordering, which fx.Module route registration can run ahead of. Safe for concurrent use.

func (*App) Static

func (a *App) Static(urlPrefix, dir string)

Static serves the files in the local directory dir at the URL prefix urlPrefix — app.Static("/media", "media") makes ./media/cat.png reachable at /media/cat.png. The prefix is mounted under the deployment route prefix when one is set.

This is the guarded counterpart to Engine().Static(). gin panics at boot when a static mount registers a /*filepath catch-all at the root, which is what happens whenever the prefix is blank or "/": the catch-all collides with framework routes (the /__nexus dashboard, your API, the SPA fallback) and takes the whole app down. A blank/root prefix is exactly what an unset config value yields — e.g. config.Get on a key that isn't in the config store returns "" — so the failure is easy to hit by accident.

Static refuses to crash for it: a blank, root, or /__nexus-shadowing prefix is logged and skipped, the app keeps booting, and the misconfiguration shows up in the logs instead of a panic stack. A valid prefix mounts exactly like Engine().Static.

func (*App) Value

func (a *App) Value(key any) (any, bool)

Value returns a previously SetValue'd value, or (nil, false) if absent.

func (*App) Version

func (a *App) Version() string

Version is the binary's release tag, defaulting to "dev". Surfaced on /__nexus/config.

func (*App) ViteHot

func (a *App) ViteHot() *vitehot.Reader

ViteHot returns the reader for the dev-server hot file nexus-vite-plugin writes, or nil when no frontend was registered. First-party extensions use it to find the Vite dev server instead of guessing — inertia's page shell is the other consumer besides Frontend. Its Current reports a dev server only while that server is alive; a file left by one that has exited reads as absent (see vitehot.Reader.Current).

type ArgOption

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

ArgOption is returned by nexus.Arg; it applies to AsRest and AsQuery/AsMutation registrations. Repeated Arg options append, so Arg("id"), Arg("name") is equivalent to Arg("id", "name").

func Arg

func Arg(names ...string) ArgOption

Arg names the wire argument(s) for a handler that takes bare scalars instead of an args struct, killing the one-line adapter such methods otherwise force. A registration option, next to Op/Requires/Envelope:

// func (s *UserService) GetUser(id uint) (*UserDetail, error)
nexus.AsQuery((*UserService).GetUser, nexus.Arg("id"), nexus.Op("userShow"))
nexus.AsRest("GET", "/users/:id", (*UserService).GetUser, nexus.Arg("id"))

// func (s *UserService) Move(ctx context.Context, id uint, employerID int) (bool, error)
nexus.AsMutation((*UserService).Move, nexus.Arg("id", "employerId"))

Names map POSITIONALLY onto the handler's last len(names) parameters (Go reflection cannot see parameter names, so positional is the only possible mapping — double-check the order when two args share a type). Everything before them keeps its normal classification: receiver and other deps are DI-injected, context.Context fills from the request.

The single- or multi-field args struct is synthesized at registration — each field tagged json/query/path/graphql under its name — so binding, the GraphQL schema, validation surfaces and the generated SDK see exactly what a hand-written wrapper struct would have declared. A non-pointer parameter becomes a REQUIRED argument; a pointer parameter an optional one. The op name still derives from the method itself (GetUser → getUser).

Guidance: one or two scalars ride Arg well; three or more deserve a dto — the struct's field names then document the call. A parameter that is already a struct is rejected at boot ("register it directly"), and Arg on a handler that declares Params[T] or a trailing args struct is a boot error too.

type AuthRouteOption

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

AuthRouteOption is the cross-transport carrier returned by AuthRoute. Implements both RestOption and GqlOption so the same expression can flow through AsRest, AsQuery, or AsMutation without callers caring which transport the endpoint lives on.

Mirrors the pattern in nexus.Use / MiddlewareOption: a single concrete value satisfying multiple per-transport apply interfaces, with each transport reading what it needs.

func AuthRoute

func AuthRoute(flow string) AuthRouteOption

AuthRoute marks the endpoint as part of one of the framework-aware auth flows. Three values are recognized today:

"login"   endpoint that exchanges credentials for a token /
          session cookie. The SDK calls it via auth.login(creds).
"logout"  endpoint that revokes the active session. The SDK calls
          it via auth.logout() and clears its locally-stored
          token on success.
"me"      endpoint returning the current Identity. The SDK calls
          it via auth.me() to bootstrap an existing session on
          page load (cookie-based apps) or check token freshness
          (bearer apps).

Apps stay in control of the actual handler — AuthRoute is purely a metadata marker. Works on both REST (AsRest) and GraphQL ops (AsQuery, AsMutation). The SDK auto-dispatches to the right transport based on the manifest's recorded transport tag:

nexus.AsRest("POST", "/api/login", NewLogin, nexus.AuthRoute("login"))
nexus.AsMutation(NewLogin, nexus.AuthRoute("login"))
nexus.AsQuery(NewMe, nexus.AuthRoute("me"))

AuthRoute does not gate access — combine with auth.Optional() (for /me on bearer apps) or auth.Required() (for /logout) as needed.

Unknown flow values are accepted but ignored by the SDK. The recognized set may grow in future framework versions; the tag is the contract.

type BootCheck

type BootCheck func() []manifest.Issue

BootCheck is a boot-time self-check: it inspects live app topology after wiring and returns any foot-guns as manifest.Issues. It exists to promote failures that would otherwise only surface at runtime — e.g. pubsub's "topic has no transport bound", which today fails at the first Publish (possibly at 2am) — into a loud, early report at boot in dev, so a junior sees the problem before deploy. See ERRORS.md.

type BoundHandler

type BoundHandler func(ctx context.Context, args any) (any, error)

BoundHandler is the closure form an extension dispatcher invokes per request. ctx is the per-call context (with deadlines, trace IDs, etc.), args is a value assignable to ArgsType (typically a freshly-decoded struct value).

The returned any is the handler's first return value; the error is its second. Nil-pointer-or-interface results collapse to a nil any, matching the existing graphql / REST conventions so downstream marshallers don't have to special-case them.

type ClientContributorFunc

type ClientContributorFunc func(GenerateContext) ([]GeneratedFile, error)

ClientContributorFunc is the per-plugin callback that turns the active GenerateContext into a list of files the frontend codegen merges into its output tree (served on <client path>/contributions.json).

Errors propagate to the contributions request — the CLI aborts the codegen run rather than writing a partial tree.

type ClientContributorRecord

type ClientContributorRecord struct {
	PluginName string
	Contribute ClientContributorFunc
}

ClientContributorRecord pairs a contributor's callback with the plugin that registered it. The plugin name powers error reporting (the contributions route attributes failures to a specific contributor) and keeps registration order observable for tests.

type Code

type Code string

Code classifies a request-time failure. Every transport renders an error through one table keyed by its code: an HTTP status and a {code, message, errors} body on REST, extensions.code on GraphQL, the error envelope on WebSocket, a flash + 303 or the error page on Inertia.

A Code is itself an error, so a handler may return one bare (`return nil, nexus.NotFound`), and callers match with errors.Is:

if errors.Is(err, nexus.NotFound) { … }
const (
	InvalidInput    Code = "INVALID_INPUT"     // 422 — bad arguments; carries per-field messages
	Unauthenticated Code = "UNAUTHENTICATED"   // 401
	Forbidden       Code = "FORBIDDEN"         // 403
	NotFound        Code = "NOT_FOUND"         // 404
	Conflict        Code = "CONFLICT"          // 409
	TooMany         Code = "TOO_MANY_REQUESTS" // 429
	Unavailable     Code = "UNAVAILABLE"       // 503
	Internal        Code = "INTERNAL"          // 500 — also every error without a code
)

func CodeOf

func CodeOf(err error) Code

CodeOf is ErrorOf(err).Code, "" for nil.

func (Code) Error

func (c Code) Error() string

Error implements error with the code's default message.

func (Code) HTTPStatus

func (c Code) HTTPStatus() int

HTTPStatus is the code's REST status.

type Compute

type Compute[T any] func(context.Context) (T, error)

Compute is the per-request derivation behind a Scoped value.

type ConnectionCheck added in v2.4.0

type ConnectionCheck func(ctx context.Context) error

ConnectionCheck decides whether a long-lived connection (an AsWS socket, a live view page) may go on: it runs before each message with the connection's context, and an error closes the connection with it. extension/auth registers one that ends connections whose credential was revoked.

type ControllerRouter

type ControllerRouter[T any] struct {
	*Router
	// contains filtered or unexported fields
}

ControllerRouter is a Router bound to one controller type: a struct whose methods are the actions. The controller is constructed once through DI (its dependencies are its constructor's parameters), every action shares the router's prefix and gates, and the whole controller shows as one module on the dashboard.

type UsersController struct{ users *UserService }

func NewUsersController(users *UserService) *UsersController { … }

func (c *UsersController) Show(ctx context.Context, id int64) (*User, error)
func (c *UsersController) Suspend(ctx context.Context, id int64, in SuspendInput) error

nexus.Controller[*UsersController]("/users", auth.Required()).
    Provide(NewUsersController).
    Get("/:id", (*UsersController).Show).
    Post("/:id/suspend", (*UsersController).Suspend, auth.Requires("users:suspend"))

Actions are method expressions on the controller type. Bare scalar parameters bind from the route's path parameters by position — the route above gives Show and Suspend their id with no nexus.Arg — and a trailing struct is the request body (see nexus.Arg). An explicit nexus.Arg on the action overrides the inference.

A controller that implements ActionAuthorizer has Authorize called before every action, with the request's context and the action's method name.

A *ControllerRouter is an Option (pass it to Boot/Run, or include its Router in a parent with Include).

func Controller

func Controller[T any](prefix string, shared ...MiddlewareOption) *ControllerRouter[T]

Controller creates a ControllerRouter for controller type T (typically a pointer to a struct) mounted at prefix. The dashboard module is named after the type: UsersController → "users". The prefix is a REST prefix: GraphQL actions serve on the endpoint of the enclosing nexus.Module (or the app's), never on <prefix>/graphql. Inside Module("x", Path("/x"), …) the prefix stacks under /x.

func Resource

func Resource[T any](prefix string, shared ...MiddlewareOption) *ControllerRouter[T]

Resource creates a ControllerRouter for T and registers its conventional actions — whichever of these methods the controller defines:

Index    GET    <prefix>
Show     GET    <prefix>/:id
Create   POST   <prefix>
Update   PUT    <prefix>/:id   (and PATCH)
Destroy  DELETE <prefix>/:id

Path parameters bind as for Controller: Show(ctx, id int64) gets the :id, and a nested resource at "/posts/:postId/comments" gives its actions the postId too (Show(ctx, postID, id int64)). Add further actions with Member, Collection or the verb methods.

func (*ControllerRouter[T]) ActionDefaults

func (c *ControllerRouter[T]) ActionDefaults(fn func(method, path, action string) []RestOption) *ControllerRouter[T]

ActionDefaults sets the options every REST action on c starts from, chosen per action — the hook a flavour of controller uses to give custom actions its own rendering. extension/inertia's Resource sets it so a custom GET is a page and a custom write redirects, exactly like the conventional actions:

c.ActionDefaults(func(method, path, action string) []nexus.RestOption {
    return []nexus.RestOption{nexus.WithIcon("zap")}
})

method and path are the action's (path relative to the prefix); action is its method name. The defaults apply before the action's own options, so an explicit option wins; nexus.NoActionDefaults() on an action skips them. It applies to actions registered before and after the call. Calls add up: each function's options apply after the previous one's, so defaults set on an inertia.Resource extend its page rendering rather than replace it.

func (*ControllerRouter[T]) Collection

func (c *ControllerRouter[T]) Collection(method, name string, action any, opts ...RestOption) *ControllerRouter[T]

Collection registers a resource collection action at <prefix>/<name>: Collection("GET", "search", (*PostsController).Search) → GET /posts/search.

func (*ControllerRouter[T]) Delete

func (c *ControllerRouter[T]) Delete(path string, action any, opts ...RestOption) *ControllerRouter[T]

Delete registers action at DELETE path.

func (*ControllerRouter[T]) Get

func (c *ControllerRouter[T]) Get(path string, action any, opts ...RestOption) *ControllerRouter[T]

Get registers action at GET path (relative to the controller's prefix).

func (*ControllerRouter[T]) Member

func (c *ControllerRouter[T]) Member(method, name string, action any, opts ...RestOption) *ControllerRouter[T]

Member registers a resource member action at <prefix>/:id/<name>: Member("POST", "publish", (*PostsController).Publish) → POST /posts/:id/publish.

func (*ControllerRouter[T]) Mutation

func (c *ControllerRouter[T]) Mutation(action any, opts ...GqlOption) *ControllerRouter[T]

Mutation registers action as a GraphQL mutation.

func (*ControllerRouter[T]) Patch

func (c *ControllerRouter[T]) Patch(path string, action any, opts ...RestOption) *ControllerRouter[T]

Patch registers action at PATCH path.

func (*ControllerRouter[T]) Post

func (c *ControllerRouter[T]) Post(path string, action any, opts ...RestOption) *ControllerRouter[T]

Post registers action at POST path.

func (*ControllerRouter[T]) Provide

func (c *ControllerRouter[T]) Provide(fns ...any) *ControllerRouter[T]

Provide adds constructors (usually the controller's own) under the controller's module.

func (*ControllerRouter[T]) Put

func (c *ControllerRouter[T]) Put(path string, action any, opts ...RestOption) *ControllerRouter[T]

Put registers action at PUT path.

func (*ControllerRouter[T]) Query

func (c *ControllerRouter[T]) Query(action any, opts ...GqlOption) *ControllerRouter[T]

Query registers action as a GraphQL query (its op name comes from the method name). Scalar parameters need an explicit nexus.Arg — GraphQL has no path.

func (*ControllerRouter[T]) RequireActions

func (c *ControllerRouter[T]) RequireActions(msg string) *ControllerRouter[T]

RequireActions fails the boot with msg when the controller ends up with no actions at all — conventional, custom or annotated.

func (*ControllerRouter[T]) Rest

func (c *ControllerRouter[T]) Rest(method, path string, action any, opts ...RestOption) *ControllerRouter[T]

Rest registers action at method + path.

func (*ControllerRouter[T]) Reverse added in v2.22.0

func (c *ControllerRouter[T]) Reverse(ctx context.Context, action any, params ...any) (string, error)

Reverse is ControllerRouter.URL with the error returned.

func (*ControllerRouter[T]) Supply

func (c *ControllerRouter[T]) Supply(vals ...any) *ControllerRouter[T]

Supply adds a ready-made controller (or other values) under the controller's module — the alternative to a constructor via Provide.

func (*ControllerRouter[T]) TrailingSlash

func (c *ControllerRouter[T]) TrailingSlash() *ControllerRouter[T]

TrailingSlash registers every REST action at its path and at the path with a trailing slash — /users/:id and /users/:id/ — for apps whose existing links use both (a Django port, say). An action at the prefix itself serves /users and /users/. It applies to actions registered before and after the call.

func (*ControllerRouter[T]) URL added in v2.22.0

func (c *ControllerRouter[T]) URL(ctx context.Context, action any, params ...any) string

URL builds the URL of one of the controller's actions — a method expression, (*UsersController).Show.

type CronBuilder

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

CronBuilder accumulates optional metadata before Handler registers the job with the scheduler.

func (*CronBuilder) Describe

func (c *CronBuilder) Describe(desc string) *CronBuilder

Describe sets a human-readable description shown on the dashboard.

func (*CronBuilder) Handler

func (c *CronBuilder) Handler(fn func(ctx context.Context) error)

Handler finalizes the registration. A bad schedule is logged and the job is dropped; the app keeps running.

func (*CronBuilder) Service

func (c *CronBuilder) Service(name string) *CronBuilder

Service groups the cron under a service on the dashboard. Optional.

type DashboardHiddenOption

type DashboardHiddenOption struct{}

DashboardHiddenOption is the cross-transport carrier returned by HideFromDashboard — implements RestOption, GqlOption, and WSOption so one expression flows through any endpoint builder, mirroring PublicOption. It stamps registry.HiddenTag on the endpoint's tags, which the registry's VisibleEndpoints() accessor (used by every dashboard data path) filters on.

func HideFromDashboard

func HideFromDashboard() DashboardHiddenOption

HideFromDashboard marks an endpoint as exempt from the introspection dashboard (/__nexus): it is dropped from /__nexus/endpoints, the live snapshot, and the architecture graph. The endpoint STILL routes and serves requests normally — this is dashboard-only visibility, not a 404 and not an auth gate. Useful for internal/debug/health ops you don't want cluttering the topology. Works on REST (AsRest), GraphQL (AsQuery / AsMutation), and WS (AsWS):

nexus.AsRest("GET", "/internal/debug", NewDebug, nexus.HideFromDashboard())
nexus.AsQuery(NewInternalReport, nexus.HideFromDashboard())
nexus.AsWS("/events", "debug.tap", NewDebugTap, nexus.HideFromDashboard())

type DescribeOption

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

DescribeOption is the cross-transport carrier returned by Describe — it implements RestOption, GqlOption, and WSOption so one value flows through any endpoint builder, mirroring IconOption and DashboardHiddenOption. It sets the shared baseEndpointConfig.description that registerEndpoint stamps onto the registry entry for every transport.

func Describe

func Describe(s string) DescribeOption

Describe sets an endpoint's human-readable description — shown on the introspection dashboard (/__nexus) and, for GraphQL, emitted into the generated SDL documentation. Cross-transport: one expression works on REST (AsRest), GraphQL (AsQuery / AsMutation), and WS (AsWS), mirroring HideFromDashboard / WithIcon.

nexus.AsRest("POST", "/devices", NewRegister, nexus.Describe("Register a device"))
nexus.AsQuery(NewSearchUsers, nexus.Describe("Full-text user search"))
nexus.AsWS("/events", "chat.send", NewChatSend, nexus.Describe("Send a chat message"))

Describe supersedes the transport-specific Desc (GraphQL) and Description (REST) helpers, which remain for compatibility.

type Document

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

Document is the page shell the app renders into, in the DI graph so middleware and page renderers take it as a parameter rather than reading the embed — which under nexus dev would be stale, since pages then render into the document Vite serves:

func ThemeHead(doc *nexus.Document) middleware.Middleware { … }
nexus.Middleware(ThemeHead)

Get returns the current one: the built index.html in production, Vite's live one under nexus dev, or ErrNoFrontendDocument when there is none.

func (*Document) Get

Get returns the document pages render into now.

type EmptyRenderer

type EmptyRenderer interface {
	RenderEmpty(c *httpx.Ctx) error
}

EmptyRenderer is an optional companion to ResponseRenderer for handlers that return only an error: on success the framework calls RenderEmpty instead of writing a bare status. Inertia's resource actions use it so a Destroy that returns just an error still redirects.

type EndpointGate

type EndpointGate struct {
	// Middleware is the gate. It should declare AllTransports so the same
	// value gates every transport; a transport it doesn't implement is
	// simply not gated.
	Middleware middleware.Middleware
}

EndpointGate is a middleware the framework applies to every endpoint by default — the primitive behind deny-by-default auth. An extension supplies one (e.g. auth's Authorization.Default = Authenticated()) and the framework prepends it to each endpoint's chain across REST, GraphQL, and WS unless the endpoint opts out with Public(). It lives here, not in the auth extension, so package nexus can honor the policy without importing the extension that configures it (auth imports nexus, never the reverse).

type EndpointOption

type EndpointOption interface {
	RestOption
	GqlOption
	WSOption
}

EndpointOption is the cross-transport per-op option contract: one value that every endpoint builder accepts — AsRest, AsQuery / AsMutation, and AsWS. It exists so "works on any transport" has a name instead of being an unwritten convention you infer from the fact that a type happens to implement RestOption, GqlOption, and WSOption all at once.

The framework's built-in cross-transport options satisfy it: Public(), Describe(), WithIcon(), HideFromDashboard(), and Use() (hence auth.Required() / auth.Requires(), which return MiddlewareOption). The compile-time assertions below enforce that — add any new cross-transport option to the list so a regression that drops one transport fails to build rather than silently narrowing the option.

Write your own cross-transport option by implementing the three applyTo* methods and returning EndpointOption:

func WithAudit(tag string) nexus.EndpointOption { return auditOption{tag} }

Transport-specific options deliberately do NOT satisfy this — e.g. the GraphQL-only OnService returns GqlOption and is rejected by AsRest/AsWS at compile time, which is the intended guard.

type EnvelopeOption

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

EnvelopeOption is returned by nexus.Envelope. It applies to both AsRest and AsQuery/AsMutation registrations.

func Envelope

func Envelope[T, W any](wrap func(T, error) (W, error)) EnvelopeOption

Envelope declares a response envelope for one endpoint: a function the framework pipes the handler's (result, error) through before the wire write, so handlers (and service methods registered directly) return plain (T, error) while the API keeps a custom success/failure shape.

wrap is `func(T, error) (W, error)` — T assignable from the handler's result type, W the wire type — checked by the COMPILER, and invoked directly per request (a typed closure, not reflection; the generic signature is what keeps the envelope off the reflect.Call path). The app owns the shape; instantiate a generic helper per registration:

func Wrap[T any](v T, err error) (*Response[T], error) {
    if err != nil {
        return &Response[T]{Status: false, Message: err.Error()}, nil
    }
    return &Response[T]{Status: true, Data: v}, nil
}

nexus.AsQuery((*UserService).ListUsers, nexus.Envelope(Wrap[[]UserRow]))

On GraphQL the schema (and the generated SDK) declare W, not T — the envelope is part of the contract, not a serialization trick. The wrap receives a handler's error as the *nexus.Error it maps to (ErrorOf: its code, and an uncoded error's message hidden outside nexus dev), so err.Error() is safe to put on the wire. An error the wrap converts into a value (the usual case) reaches the client as a normal 200/data response; an error the wrap returns follows the transport's standard error path. Binding and validation failures happen before the handler runs and are NOT enveloped. REST + GraphQL only.

type Error

type Error struct {
	Code    Code
	Message string              // shown to the client; the code's default when empty
	Fields  map[string][]string // per-field messages (InvalidInput); global ones under GlobalErrorKey
	Cause   error
	// RetryAfter, when set (TooMany, Unavailable), is sent on REST as the
	// Retry-After header, in whole seconds.
	RetryAfter time.Duration `json:"-"`
}

Error is the one request-time error model. Handlers return it (or any error wrapping it); an error without one renders as Internal.

return nil, nexus.Err(nexus.NotFound, "user not found")
return nil, nexus.Invalid().Field("email", "already taken")

errors.Is and errors.As see through Cause.

func Err

func Err(code Code, message string) *Error

Err returns an error with the given code and message.

func Errf

func Errf(code Code, format string, args ...any) *Error

Errf is Err with a format; a %w verb also sets Cause.

func ErrorOf

func ErrorOf(err error) *Error

ErrorOf maps any error onto the model: the *Error it wraps, a bare Code, a GraphQL argument-validation failure as InvalidInput, and anything else as Internal, whose message is shown under `nexus dev` and hidden ("internal error") otherwise — the original stays reachable as Cause. nil stays nil. Every transport renders through it; an extension writing an error response itself should too.

func Invalid

func Invalid() *Error

Invalid starts an InvalidInput error to accumulate messages into:

errs := nexus.Invalid()
if taken { errs.Field("email", "already taken") }
if down { errs.Global("payment provider unreachable") }
if errs.Any() { return nil, errs }

Field keys should match the args struct's json/form names so the client binds each message to its input.

func (*Error) Any

func (e *Error) Any() bool

Any reports whether any field (or global) message has been recorded — the guard before returning an Invalid() accumulator.

func (*Error) Error

func (e *Error) Error() string

Error is the message, else the code's default (naming the failed fields of an InvalidInput).

func (*Error) Extensions

func (e *Error) Extensions() map[string]any

Extensions implements graphql-go's ExtendedError: extensions.code, and the field map under extensions.errors.

func (*Error) Field

func (e *Error) Field(field, message string) *Error

Field records a message against a field. Repeated calls accumulate.

func (*Error) First

func (e *Error) First() map[string]string

First returns the first message per field — the flat map[field]message shape Inertia's useForm expects in the errors prop.

func (*Error) Global

func (e *Error) Global(message string) *Error

Global records a message not tied to any one field, under GlobalErrorKey.

func (*Error) HTTPStatus

func (e *Error) HTTPStatus() int

HTTPStatus is the error's REST status.

func (*Error) Is

func (e *Error) Is(target error) bool

Is matches a Code: errors.Is(err, nexus.NotFound).

func (*Error) MarshalJSON

func (e *Error) MarshalJSON() ([]byte, error)

MarshalJSON writes the body every JSON transport sends: {"code", "message", "errors"}.

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorRenderer

type ErrorRenderer interface {
	RenderError(c *httpx.Ctx, err error) (handled bool, rerr error)
}

ErrorRenderer is an optional companion to ResponseRenderer: when a renderer also implements it, the framework offers handler *errors* to it before the default error write. This is how Inertia turns a handler that returns inertia.Redirect(...) / inertia.Location(...) into a 303/409 redirect rather than a JSON 500.

RenderError reports handled=true when it took ownership of the response (the default error write, trace error-wrapping, and status mapping are then all skipped — a redirect is not an error to log). Returning handled=false leaves the error to the standard path unchanged. A non-nil error return is treated like a renderer failure (500 if nothing was written).

type ExtensionDecoder

type ExtensionDecoder func(rawTOML []byte) ([]Option, error)

ExtensionDecoder turns the raw TOML bytes of one [extensions.<name>] sub-tree into the nexus.Option(s) that wire the extension into nexus.Run. The decoder owns its schema — operators write TOML keys the decoder defines, the decoder unmarshal()s them however it likes (typed struct, generic map, whatever).

Returns the decoded Options + an error. Empty/nil Options + nil error means "successfully decoded but the block has no effect" (e.g. all fields zero); the framework treats it as a no-op.

Why bytes rather than a typed struct: we don't know the extension's schema at framework-level, so we leave that decision to the decoder. Re-marshaling adds ~µs per extension at boot; negligible compared to the rest of startup cost.

func LookupExtensionDecoder

func LookupExtensionDecoder(name string) ExtensionDecoder

LookupExtensionDecoder returns the registered decoder for name, or nil when none is registered. Exposed for the lint command (so it can warn on [extensions.X] blocks for which no decoder exists — typically because the operator forgot to import the extension package).

type Form

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

Form is the raw-input escape hatch for handlers whose input is genuinely dynamic — file uploads, variable-key forms, Django-view migrations. Declare it as a handler parameter (framework-filled, like *httpx.Ctx):

func NewUploadCv(svc *Svc, ctx context.Context, fm *nexus.Form) (any, error) {
    title := fm.Get("title")
    cv, err := fm.File("cv")
    ...
}

Reads are SOURCE-UNIFIED: Get/All/File see the same fields whether the client sent multipart/form-data (what Inertia's useForm switches to when a file is attached), application/x-www-form-urlencoded, or a JSON body (what useForm sends otherwise); the URL query is the lowest-precedence fallback. So a working form does not break the day a file input is added to it.

Prefer the typed shape — `func(ctx, args T)` / Params[T] — whenever the fields are known: validation tags, GraphQL schema, the typed SDK, and maskid unmasking all ride the args struct and none of them see fm.Get. Note raw reads bypass maskid: a masked id read via Get stays a string. Bind is the bridge back into the typed world.

REST/Inertia only: on GraphQL and WS the parameter is a typed nil (every method no-ops), the same contract *httpx.Ctx has there.

func FormFrom

func FormFrom(ctx context.Context) *Form

FormFrom returns the request's Form from a context. Available beneath a handler that declares a *Form parameter (the injection wraps the request context); elsewhere it returns nil — check before use, or take the Form as a handler param and pass it down explicitly.

func (*Form) All

func (f *Form) All(key string) []string

All returns every value for a repeated field (or a JSON array of scalars).

func (*Form) Bind

func (f *Form) Bind(ptr any) error

Bind is the bridge back into the typed world: binds the request into a tagged args struct exactly as reflective registration would (json / form / query / header / path tags), safe to call after raw reads — the JSON body is re-served, and multipart/urlencoded fields are already parsed.

func (*Form) Bool

func (f *Form) Bool(key string, def bool) bool

Bool parses the field as a boolean ("true"/"1"/"on" → true), returning def when absent or unrecognized.

func (*Form) File

func (f *Form) File(key string) (*FormFile, error)

File returns the first uploaded file for the key, or an error naming the key when the request carried no such file.

func (*Form) Files

func (f *Form) Files(key string) []*FormFile

Files returns every uploaded file for the key — variable-count upload inputs are the canonical reason Form exists. Nil when none.

func (*Form) Get

func (f *Form) Get(key string) string

Get returns the field's first value, "" when absent.

func (*Form) Int

func (f *Form) Int(key string, def int) int

Int parses the field as an integer, returning def when absent or unparsable.

func (*Form) Lookup

func (f *Form) Lookup(key string) (string, bool)

Lookup distinguishes an absent field from an empty one.

func (*Form) Value

func (f *Form) Value(key string) any

Value returns the raw decoded JSON value for a key — the door to nested objects and mixed arrays that Get's flat view cannot carry. Nil for non-JSON bodies or absent keys.

type FormFile

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

FormFile describes one uploaded file. Open streams the part — spilled to a temp file by the multipart parser when large, never fully buffered by nexus — so GB-scale uploads cost memory only up to the parser's spill threshold.

func (*FormFile) ContentType

func (ff *FormFile) ContentType() string

func (*FormFile) Name

func (ff *FormFile) Name() string

func (*FormFile) Open

func (ff *FormFile) Open() (multipart.File, error)

func (*FormFile) Size

func (ff *FormFile) Size() int64

type FrontendDocument

type FrontendDocument struct {
	// HTML is the document. With a live Vite dev server announced by the hot
	// file it is Vite's transformed index.html, every root-relative asset URL
	// pointed at that server; otherwise it is the built bundle's index.html.
	HTML []byte
	// FromDevServer reports the first case: the scripts are live dev
	// modules, and the page must not be cached.
	FromDevServer bool
}

FrontendDocument is the HTML document a server-rendered page is built from: the app's index.html as the browser should receive it right now. It lets a page renderer (inertia) keep everything the app put in index.html — title, meta, stylesheets, loaders — instead of synthesising a second document that has to repeat them.

type FrontendOption

type FrontendOption interface {
	// contains filtered or unexported methods
}

FrontendOption tunes a Frontend call. Returned by helpers like FrontendAt; users don't construct these directly.

func FrontendAt

func FrontendAt(path string) FrontendOption

FrontendAt sets a sub-path the SPA is served under, in addition to the deployment-wide route prefix. The two compose: deployment prefix /v1 + FrontendAt("/admin") → SPA at /v1/admin/. Useful when API endpoints live at the deployment root and the frontend should answer on a sibling path. Empty / "/" mean the SPA mounts directly under the deployment prefix (the default).

Trailing slashes are trimmed; a leading slash is added if missing. Pass "/admin" or "admin" — both resolve to "/admin".

type GenerateContext

type GenerateContext struct {
	Registry *registry.Registry
	Refs     map[string]registry.NamedType
	BasePath string
	Extras   map[string]any
}

GenerateContext is the input handed to a client contributor. It reads from the live registry and the shared named-type pool to project TS source files (or any other generated artifact) without re-walking the schema.

Extras is a free-form map carrying framework-specific knobs (Vue vs React, public manifest flags, etc.) without baking them into this struct. Convention: keys live in the owning package's namespace ("frontend.framework", not "framework").

type GeneratedFile

type GeneratedFile struct {
	Path string
	Body []byte
}

GeneratedFile is one file a client contributor adds to the frontend codegen tree. Path is forward-slash relative to the tree root; Body is the raw bytes. Mirrors extension.File so the extension package can convert values across the package boundary without an import cycle.

type GqlOption

type GqlOption interface {
	// contains filtered or unexported methods
}

GqlOption tunes a GraphQL registration. An interface (not a func type) so a single value — notably the nexus.Use cross-transport bundle — can satisfy both GqlOption and RestOption by implementing each's applyToX.

func Deprecated

func Deprecated(reason string) GqlOption

Deprecated marks the field deprecated. The reason shows up in SDL and the dashboard "deprecated" badge.

func GraphMiddleware

func GraphMiddleware(name, description string, mw gql.Middleware) GqlOption

GraphMiddleware attaches a named GraphQL-only middleware to the field. The name appears in the endpoint's middleware list on the dashboard (and "auth", "cors", etc. get labelled "builtin" via nexus/middleware.Builtins).

nexus.AsQuery((*UserService).ListUsers,
    nexus.GraphMiddleware("audit", "logs every resolve", Audit))

func Audit(next gql.Resolver) gql.Resolver {
    return func(f gql.Field) (any, error) { return next(f) }
}

For cross-transport middleware, prefer nexus.Use(middleware.Middleware{...}) — it accepts the same bundle on REST and GraphQL alike.

func OnService

func OnService[S any]() GqlOption

OnService routes this registration onto the given service wrapper type without requiring the handler to take it as a dep. Use when the handler is minimal (`func NewListQuestions(q *QuestionsDB) (...)`) but still belongs to a particular service on the dashboard.

nexus.AsQuery(NewListQuestions, nexus.OnService[*OrdersService]())

The resolver still needs the owning service to have been provided into the fx graph elsewhere so MountGraphQL can pick up the field.

func Op

func Op(name string) GqlOption

Op overrides the inferred op name.

func RateLimit

func RateLimit(l ratelimit.Limit) GqlOption

RateLimit declares a baseline rate limit for this op. The auto-mount registers it with the app's rate-limit store and wires an enforcement middleware that consults the store on every request. Operators can override the effective limit live from the dashboard — the declared baseline stays in source-of-truth, the override survives in the store.

nexus.AsMutation(NewCreateOrder,
    nexus.RateLimit(ratelimit.Limit{RPM: 30, PerIP: true}),
)

Burst defaults to RPM/6 when zero (10-second burst window). Set PerIP to true to scope the bucket to the caller's IP; leave false for a shared global bucket.

type HandlerShape

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

HandlerShape is the export-facing wrapper around the framework's internal handlerShape. Extensions (extension/peer, future RPC transports, custom auth bundles) that want to mount user handlers using the canonical reflective signature go through this type.

The public surface is intentionally narrow: depTypes for fx wiring, argsType for body decoding, hasArgs/hasCtx for slot decisions, and Invoke for the actual call. Everything else stays unexported so the internal shape can evolve without breaking out-of-tree code.

func InspectHandlerForExt

func InspectHandlerForExt(fn any) (HandlerShape, error)

InspectHandlerForExt is the public version of inspectHandler. Extensions call this once at registration time, then use the returned HandlerShape to build an di.Invoke that resolves deps and stamps a bound closure into the extension's dispatch table.

Shape constraints match every other reflective registration in nexus — see the package doc on AsRest for the full grammar.

Errors here are returned to the caller as a Go error rather than wrapped in an di.Error option, because the caller usually wants to attach its own context ("peer.AsCall(%q): %w") before letting fx see them.

func (HandlerShape) ArgsType

func (h HandlerShape) ArgsType() reflect.Type

ArgsType returns the struct type the handler decodes its body into — the T in Params[T] (or the trailing flat-args struct for legacy handlers). nil when the handler takes no args.

func (HandlerShape) BuildInvokeOption

func (h HandlerShape) BuildInvokeOption(mount func(app *App, bound BoundHandler) error) Option

BuildInvokeOption produces a nexus.Option whose underlying di.Invoke has the signature `(*App, dep1, dep2, ...) → ()`. When fx fires the invoke at app start, it resolves every dep type returned by DepTypes, captures them in a BoundHandler closure, and hands the closure to mount.

Extensions use this as the single source of fx wiring — they don't need to assemble reflect.FuncOf signatures themselves. Each extension's AsX option boils down to:

sh, err := nexus.InspectHandlerForExt(fn)
if err != nil { return ... }
return sh.BuildInvokeOption(func(app *App, bound BoundHandler) error {
    extDispatchTable.Store(name, bound)
    return nil
})

The mount closure receives the App so it can read app-level state (engine, registry, plugin store) before stashing the bound handler.

func (HandlerShape) DepTypes

func (h HandlerShape) DepTypes() []reflect.Type

DepTypes returns the reflective types of every fx-injected dep the handler expects, in registration order. Extension code uses this to build an di.FuncOf with the same signature so fx resolves the deps at boot.

func (HandlerShape) HasArgs

func (h HandlerShape) HasArgs() bool

HasArgs reports whether the handler expects an args struct. Extensions use this to decide whether to allocate + decode a body before invoking.

func (HandlerShape) ReturnType

func (h HandlerShape) ReturnType() reflect.Type

ReturnType returns the handler's first return type (the result). nil when the handler returns only an error (or nothing). Extensions use this for response shape inspection — schema emission, dashboard endpoint metadata.

type Hook

type Hook = di.Hook

Lifecycle and Hook are re-exported from the di seam so extensions can take a lifecycle parameter and register start/stop hooks without importing di directly. The builtin container provides Lifecycle natively; the opt-in fx adapter bridges fx.Lifecycle onto it.

type IconOption

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

IconOption is the cross-transport carrier returned by WithIcon — implements RestOption, GqlOption, and WSOption so one expression flows through any endpoint builder, mirroring HideFromDashboard. It stamps registry.IconTag on the endpoint's tags, which the dashboard reads when rendering the node.

func WithIcon

func WithIcon(name string) IconOption

WithIcon sets the dashboard icon for an endpoint — a lucide-style icon name rendered on the endpoint's node in the architecture graph and the endpoints list. Its main use is branding: an extension that registers endpoints through a custom decorator stamps its OWN icon so its endpoints are recognizable in the topology (e.g. inertia.Page → the inertia icon, widgets.Panel → a panel icon). Cross-transport: works on REST, GraphQL, and WS.

// inside an extension's decorator-form registrar:
decorate.Record(nexus.AsRest("GET", "/widgets"+path, ctor, nexus.WithIcon("layout-panel-top")))

The endpoint still routes and serves normally; this is dashboard presentation only. An empty name is ignored (the per-transport default icon shows).

type IdentityRestorer added in v2.7.0

type IdentityRestorer func(ctx context.Context, app *App, id string) (context.Context, error)

IdentityRestorer rebuilds, for work that runs outside the request that started it (a background job), the context a request by user id would have had: who they are, as of now. extension/auth registers one.

type Lifecycle

type Lifecycle = di.Lifecycle

Lifecycle and Hook are re-exported from the di seam so extensions can take a lifecycle parameter and register start/stop hooks without importing di directly. The builtin container provides Lifecycle natively; the opt-in fx adapter bridges fx.Lifecycle onto it.

type MiddlewareOption

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

MiddlewareOption carries a Middleware across the AsRest/AsQuery/... call sites. Each transport's option type embeds / converts this, so a single nexus.Use(...) expression can appear wherever the transport accepts it.

MiddlewareOption also satisfies the top-level Option interface as a no-op so callers can flow it through Option-typed variadic slots. The option still only takes effect via applyToRest / applyToGql / applyToWS — the no-op nexusOption() exists purely for type-system passage.

func MaxBody

func MaxBody(n int64) MiddlewareOption

MaxBody sets the request-body cap for one endpoint, replacing the app's ([runtime.server] max_body_bytes, 32MB by default); n ≤ 0 removes it — for an upload endpoint that streams to storage, say:

nexus.AsRest("POST", "/files", (*Files).Upload, nexus.MaxBody(2<<30))

func Timeout

func Timeout(d time.Duration) MiddlewareOption

Timeout bounds one endpoint: its context is cancelled after d and the connection's read and write deadlines are set to match, so a slow client can't hold the handler past it. Long streams (SSE, downloads) simply don't set one; there is no app-wide write timeout by default.

func Use

Use attaches a transport-agnostic middleware bundle to a registration. Works on AsRest, AsQuery, AsMutation, (future AsSubscription / AsWebSocket) — each transport picks the realization it understands from the bundle (HTTP for REST/WS upgrade, Graph for GraphQL). Missing fields are silently ignored so a single bundle can degrade gracefully across transports.

rl := ratelimit.NewMiddleware(store, key, ratelimit.Limit{RPM: 30})
di.Provide(
    nexus.AsMutation(NewCreateOrder, nexus.Use(rl)),
    nexus.AsRest("POST", "/quick", NewQuick, nexus.Use(rl)),
)

For app-wide coverage (every REST endpoint + GraphQL POST + WS upgrade + the dashboard itself) put the middleware in Config.GlobalMiddleware instead of naming it on each registration.

type NexusResourceProvider

type NexusResourceProvider interface {
	NexusResources() []resource.Resource
}

NexusResourceProvider is implemented by managers that know the external resources they front. A manager's NexusResources slice is used in two places:

  1. Boot-time registration via nexus.ProvideResources — each returned resource.Resource is added to the app registry so it appears on the dashboard with its health, description, and details.
  2. Service attachment via the GraphQL auto-mount — whenever a resolver names this manager as a dep, every resource in the slice gets linked to the owning service by name, drawing the architecture edge.

A manager may list more resources than any one handler uses; the edge is drawn per named resource on every service that mentions the manager.

func (m *DBManager) NexusResources() []resource.Resource {
    var out []resource.Resource
    m.Each(func(name string, db *DB) {
        out = append(out, resource.NewDatabase(name, ...))
    })
    return out
}

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option composes a nexus app. Everything returned by Provide, Supply, Invoke, Module, AsRest, AsQuery, AsMutation, AsWebSocket, AsSubscription is an Option, ready to pass to Run. The DI container is an implementation detail — user code imports only nexus.

func AddStartupTask

func AddStartupTask(t manifest.StartupTask) Option

AddStartupTask produces an Option that registers a startup task. The task's Run is preserved through to integration step 3 where registerLifecycle invokes it before binding listeners.

func AsMutation

func AsMutation(fn any, opts ...GqlOption) Option

AsMutation is the mutation analogue of AsQuery.

func AsQuery

func AsQuery(fn any, opts ...GqlOption) Option

AsQuery registers a GraphQL query from a plain Go handler — usually a method expression. The handler's signature is inspected reflectively:

  • A *Service-wrapper parameter (e.g. *OrdersService, or the receiver) grounds the op under that service and its GraphQL endpoint.
  • Other parameters are DI-injected deps.
  • The last parameter may be an args struct (or Params[T]). Field tags drive the arguments: graphql:"name" — arg name (defaults to the json name, then the lowercased field name) graphql:"name,required" — NonNull graphql:"name,type=Status" — a type declared with RegisterGqlType validate:"required" — required validate:"len=3|120" — string length 3..120 validate:"int=1|100" — integer range 1..100 validate:"oneof=a|b|c" — one of the listed values Chain multiple rules with commas.
  • Return type must be (T, error). T is the field's type; pointer and slice wrappers are honored.

The op name is the method's (or function's) name with its first rune lowercased ("ListOrders" → "listOrders"); override with nexus.Op.

nexus.AsQuery((*OrderService).ListOrders)
nexus.AsMutation((*OrderService).CreateOrder,
    nexus.GraphMiddleware("audit", "logs every resolve", Audit))

func AsSubscription

func AsSubscription(fn any, opts ...GqlOption) Option

AsSubscription is reserved: reflective GraphQL subscriptions are not implemented yet, and registering one fails boot. Push live updates over AsWS until they are.

func AsWS

func AsWS(path, msgType string, fn any, opts ...WSOption) Option

AsWS registers one message-type-scoped handler on a WebSocket endpoint. Multiple AsWS calls with the same path share a single connection pool — the framework dispatches inbound messages by their envelope `type` to the matching handler.

type ChatPayload struct{ Text string }

func NewChatSend(svc *ChatSvc, sess *nexus.WSSession,
                 p nexus.Params[ChatPayload]) error {
    sess.EmitToRoom("chat.message",
        map[string]string{"text": p.Args.Text, "user": sess.UserID()},
        "lobby")
    return nil
}

nexus.AsWS("/events", "chat.send", NewChatSend, auth.Required())

Wire protocol — every message is wrapped in the framework's envelope:

{ "type": "chat.send", "data": {...}, "timestamp": <unix> }

The built-in types `ping`, `authenticate`, `subscribe`, `unsubscribe` are handled by the hub directly and never reach user handlers. A connection's user comes from the authenticated upgrade request (see RegisterRequestIdentity); `authenticate` only reports it. A client `subscribe` is refused unless the path allows it with ClientRooms — join rooms server-side with WSSession.JoinRoom after checking the caller.

Handler signature: same reflective convention as AsRest / AsQuery —

  • fx-injected deps anywhere (service wrappers, resources, other services);
  • an optional *nexus.WSSession parameter gets the live connection handle;
  • an optional nexus.Params[T] carries the decoded message payload in Args;
  • return (error) — a non-nil error is sent back on the same connection as an `error` envelope event. The connection stays open.

Middleware (auth.Required, rate limits, etc.) on the FIRST AsWS call for a path is installed on the HTTP upgrade route and gates every subsequent connection. Middleware declared on later AsWS calls for the same path is ignored with a warning log — all dispatches share one upgrade route.

func AsWorker

func AsWorker(name string, fn any) Option

AsWorker registers a long-lived background worker. The framework owns lifecycle — it starts the worker on di.Start in its own goroutine, cancels its context on di.Stop, and records status + last-error on the registry so the dashboard can surface it.

Signature requirements:

  • First parameter MUST be context.Context. The framework supplies a context that cancels when the app stops; workers are expected to honor it and return.

  • Remaining parameters are fx-injected deps (same rules as a constructor — they must exist in the graph).

  • Return is optional: a single (error) return lets the worker report a fatal error. context.Canceled / nil is treated as a clean stop; anything else sets Status="failed" + LastError.

    nexus.AsWorker("cache-invalidation", func(ctx context.Context, db *DB, cache *CacheManager, logger *slog.Logger) error { for !db.IsConnected() { select { case <-ctx.Done(): return ctx.Err() case <-time.After(time.Second): } } listener := pq.NewListener(db.ConnectionString(), ...) defer listener.Close() _ = listener.Listen("cache_invalidation") for { select { case <-ctx.Done(): return nil case n := <-listener.Notify: handle(n, cache) } } })

Resource / service deps (for the architecture graph) are detected the same way nexus.ProvideService does it — any param implementing NexusResourceProvider contributes its resources, any param whose type is a service wrapper contributes a service dep.

A worker panic is caught and reported as Status=failed; the app keeps running. For restart semantics, wrap your worker body in a loop that re-dials on ctx.Done() exit OR let the operator restart the app.

func ClientUse

func ClientUse(cfg client.Config) Option

ClientUse is the option-chain alias for setting Config.Client. Most apps wire the SDK via the Config field — one line on the Config literal — but ClientUse is the right choice when:

  • You want per-deployment gating: composes with IfDeployment.

    nexus.IfDeployment([]string{"public-api"}, nexus.ClientUse(client.Config{Enabled: true}), )

  • The SDK is conditional on runtime state the Config struct can't easily express (env-driven feature flags, multi-binary option chains). ClientUse + nexus.Options(...) compose freely with everything else.

Idempotent: when both Config.Client.Enabled AND ClientUse are in scope, the second mount is skipped (the App already has a live Handler from the first).

Sets cfg.Enabled=true unconditionally — the option-chain caller's intent is "mount it"; the Config-side knob exists for the value- driven path only.

func ClientUseWithContributions

func ClientUseWithContributions(cfg client.Config, buildFactory func(*App) client.ContributionsBuilder) Option

ClientUseWithContributions is ClientUse + a contributions builder factory. When buildFactory is non-nil, the resulting builder is invoked at HTTP-request time so the closure can read live state (contributor list, schema refs) that isn't available at option- construction time. The factory itself runs once inside fx.Invoke with the constructed *App in scope.

Lives in nexus/ because the App's clientHandler field is unexported — keeping the assignment inside the package avoids exposing it as a Setter.

Phase-3 caller: extension/frontend's mountClientSDK helper. Direct user-side wiring is rare; most apps go through frontend.Plugin(...) which composes this transparently.

func ControllerActions

func ControllerActions[T any](fn func(*ControllerRouter[T])) Option

ControllerActions records actions for controller type T — what the //nexus:page, //nexus:rest, //nexus:query and //nexus:mutation annotations on T's methods generate when T carries no //nexus:controller:

nexus.ControllerActions(func(c *nexus.ControllerRouter[*AdminController]) {
    c.Rest("GET", "/", (*AdminController).Dashboard, inertia.Component("Admin/Dashboard"))
    c.Query((*AdminController).AdminStats)
})

A nexus.Controller[T] or nexus.Resource[T] declared in Go takes them: they mount under its prefix, its module's Path, its gates and Authorize — so the Go code says where the controller lives and the annotations say what it does. With no such controller in the app, they register on their own, under the module the returned Option sits in.

func DeclareEnv

func DeclareEnv(e manifest.EnvVar) Option

DeclareEnv produces an Option that registers one EnvVar on the app at graph construction. Multiple calls compose:

nexus.Module("cache",
    nexus.DeclareEnv(manifest.EnvVar{Name: "REDIS_HOST", Required: true, BoundTo: "redis.host"}),
    nexus.DeclareEnv(manifest.EnvVar{Name: "REDIS_PORT", Required: true, BoundTo: "redis.port"}),
    nexus.Provide(NewManager),
)

func DeclareEnvList

func DeclareEnvList(es []manifest.EnvVar) Option

DeclareEnvList is the bulk variant of DeclareEnv. Used to splice in a slice an upstream package exposes (e.g. cache.ManifestEnv()):

nexus.Run(cfg,
    cache.Module,
    nexus.DeclareEnvList(cache.ManifestEnv()),
    ...
)

Lets a leaf package describe its env surface as static data without importing nexus (which would cycle). The app composes the declaration at boot.

func DeclareService

func DeclareService(s manifest.ServiceNeed) Option

DeclareService produces an Option that registers one ServiceNeed.

func DeclareVolume

func DeclareVolume(v manifest.Volume) Option

DeclareVolume produces an Option that registers one Volume.

func DecoratedModules

func DecoratedModules(names ...string) Option

DecoratedModules limits which //nexus:-annotated (decorate-registered) modules this boot accepts: of the registrations the deferred sources drain, only top-level modules whose name is listed participate; everything else drained is dropped. Hand-written options are never affected, and without this option every drained registration participates, as before.

It exists for tests. The decorate registry is process-global, so an InProcess boot in a test binary sees the registrations of EVERY annotated package any test file links — booting one module in isolation then fails on the other packages' providers. Scope the boot instead:

nexus.InProcess(config.Runtime{},
    nexus.DecoratedModules("adverts"),   // only adverts' //nexus: registrations
    adverts.Module, ...)

With no names, every decorated registration is dropped — a boot fully isolated from annotations. Decorated modules are named after their package (the main package registers as "app"). The option is read from the boot's top-level option list only.

func Defer added in v2.2.0

func Defer(fn func() Option) Option

Defer builds an Option at boot, when the option tree is collected — after nexus.toml is loaded and every package init has run — instead of when the option list is written. An extension whose routes come from its nexus.toml table returns them from fn. A nil result is a no-op.

nexus.Defer(func() nexus.Option {
    return nexus.AsRest("POST", mySection.Get().Path, handler)
})

func FailBoot

func FailBoot(err error) Option

FailBoot injects an error discovered while building options; it surfaces at boot instead of panicking at call time. Extensions use it to report bad config without importing the DI backend.

if err := cfg.validate(); err != nil { return nexus.FailBoot(err) }

func Frontend

func Frontend(fsys fs.FS, root string, opts ...FrontendOption) Option

Frontend mounts a built single-page-app bundle from an embedded filesystem. The classic shape:

//go:embed all:web/dist
var webFS embed.FS

nexus.Run(config.Runtime{...},
    nexus.Frontend(webFS, "web/dist"),
    users.Module,
)

The `root` argument is the directory inside fsys that holds index.html plus the asset subdirectories — typically the same path passed to //go:embed minus the `all:` prefix. Pass "" when fsys is already rooted at the dist directory (e.g. after fs.Sub).

Pass nexus.FrontendAt("/admin") (or any sub-path) to mount the SPA under a sub-path instead of at the deployment root — useful when REST/GraphQL live at /api/* and the frontend should answer at /admin/* on the same listener.

Behavior (under the deployment route prefix when one is set, then the FrontendAt mount path when one is set):

  • Files with an extension (foo.js, /assets/main.css, /favicon.ico) are served from the bundle. Cache policy comes from the build: a file is cached forever (immutable) only when the Vite manifest lists it as build output AND its name carries a content hash; everything else is revalidated through an ETag. Without a manifest only hashed names under /assets/ are cached forever. Directories are never listed, and the /.vite/ tree (the build manifest, the dev-server hot file) is never served.
  • Anything else is a client-side route and gets index.html, revalidated on every load (no-cache + ETag) so a redeployed shell is picked up at once. A build with no index.html (a module-only entry, nexus({ input: 'src/main.ts' })) has no page to fall back to: unknown routes answer 404.
  • REST / GraphQL / WebSocket / dashboard routes are registered before the NoRoute hook fires, so they win on conflict.

While a Vite dev server announces itself through nexus-vite-plugin's hot file (<root>/.vite/nexus-hot.json on disk — under nexus dev, or with environment = "development", and only while that dev server is alive), the dev server is the frontend: index.html responses are its transformed page with module URLs pointed at it, and static files are proxied to it for loopback clients — so a runtime path such as <img src="/logo.png"> or fetch("/config.json") gets the current public/ file — falling back to the bundle when it has none.

Boot: a bundle with an index.html or a Vite manifest boots. One with neither was never built and fails fast — unless the app is evidently under development right now (nexus dev, or a live Vite dev server's hot file), where a placeholder page stands in so the API and dashboard stay reachable. A config value alone never grants that leniency: nexus.toml's environment ships to production.

func IfDev

func IfDev(opts ...Option) Option

IfDev applies the supplied options ONLY when running under `nexus dev` (NEXUS_DEV=1). In production the wrapped block is a no-op — useful for dev-only stubs (config.Local, in-memory auth, fake mailers) that have no place in a real deploy.

Variadic so multiple options compose cleanly without a surrounding nexus.Options(...) call. Empty input is a no-op regardless of mode.

func IfNotDev

func IfNotDev(opts ...Option) Option

IfNotDev applies the supplied options ONLY when NOT running under `nexus dev`. The mirror image of IfDev — gate plugins that require production-grade configuration (TLS certs, signing keys, OAuth2 client secrets, config-server URLs) so `nexus dev` boots without forcing the operator to fill those in.

nexus.IfNotDev(
    tls.Module(tls.Config{Domains: []string{"app.example.com"}}),
    oauth2.Module(oauth2.Config{ClientSecret: secret}),
)

`nexus dev` skips both; `./bin/app` wires them normally.

func Invoke

func Invoke(fns ...any) Option

Invoke runs a function at startup, resolving its parameters from the graph. Use for side-effects on boot — attaching resources, registering hooks, seeding state. Multiple Invoke options run in registration order.

nexus.Invoke(func(app *nexus.App, dbs *DBManager) {
    app.OnResourceUse(dbs)
})

func LoadExtensions

func LoadExtensions(path ...string) (Option, error)

LoadExtensions reads the [extensions.*] block from nexus.toml at path (defaults to config.DefaultPath, same as config.Load), looks up each declared extension's decoder, and returns the collected Options ready to be spread into nexus.Run.

Boot calls this (with config.Load) for you — reach for it directly only for the explicit form alongside a Go-built Config.

Operators typically combine with config.Load:

cfg := config.MustLoad()
extOpts, err := nexus.LoadExtensions()
if err != nil { log.Fatal(err) }
opts := append(extOpts, /* hand-coded options */...)
nexus.Run(cfg, opts...)

Or via the convenience helper LoadExtensions which panics:

nexus.Run(config.MustLoad(), nexus.MustLoadExtensions())

Behaviour:

  • Missing file → returns ([], nil). Operators without a nexus.toml pay nothing; existing code keeps working.
  • [extensions.X] declared but no decoder registered for X → returns a wrapped error citing X. Catch via lint at CI time so the error never reaches boot.
  • Decoder errors → wrapped with the extension name so the operator knows which block was malformed.

Ordering: decoders execute in alphabetical order of name for repeatable boot behavior. If you need a specific ordering (extension A depends on B's option) wire those via Go code instead — TOML is for data, not graph dependencies.

func LoadField

func LoadField[Parent any, Key comparable, Child any](
	fieldName string,
	keyFn func(Parent) Key,
	fetch any,
) Option

LoadField registers a batched virtual field on the GraphQL Object type for Parent. The field's resolver pulls a per-request Loader from context, enqueues the parent's key, and returns a thunk that graphql-go's executor dethunks breadth-first — collapsing N individual lookups across sibling resolvers into one fetch call.

This is the framework-shaped fix for the N+1 pattern that nested GraphQL resolvers otherwise produce. Parent and Child are Go types; Key is the lookup key (typically int64 / string / UUID).

The fetch argument is one of three shapes; the framework picks the right path by reflecting on it at registration time:

// (a) Direct fetch — no fx deps. Type-check at compile time.
nexus.LoadField[User, int64, *Bank](
    "bank",
    func(u User) int64 { return u.ID },
    func(ctx context.Context, ids []int64) (map[int64]*Bank, error) {
        return db.BanksByUserIDs(ctx, ids)
    },
)

// (b) Constructor returning Fetch[K, V] — fx resolves the
//     constructor's params at boot. Inner Fetch is fully typed.
func NewBankFetcher(db *DB) dataloader.Fetch[int64, *Bank] {
    return func(ctx context.Context, ids []int64) (map[int64]*Bank, error) {
        return db.BanksByUserIDs(ctx, ids)
    }
}
nexus.LoadField[User, int64, *Bank]("bank", keyFn, NewBankFetcher)

// (c) Inline fetch with trailing fx-injected deps — fx resolves
//     the deps at boot; ctx + keys remain the head of the fn.
nexus.LoadField[User, int64, *Bank](
    "bank",
    func(u User) int64 { return u.ID },
    func(ctx context.Context, ids []int64, db *DB, cache *Cache) (map[int64]*Bank, error) {
        ...
    },
)

Wrong shapes surface as an di.Error at app start with a message describing the expected signatures.

Parent's SDL name is the Go type's reflect name (User → "User"). Type aliases unwrap to the original (`type User = users.Row` registers against "Row"); use a defined type or rename if that isn't what you want.

func Managed

func Managed[T any](name string, build func(*slog.Logger) (*T, error), resourceFor func(*T) resource.Resource) Option

Managed is the general-purpose declarative binder for any resource manager that doesn't fit the kind-specific Database[T] / Cache[T] / pubsub.Broker[T] (e.g. a custom RabbitMQ/queue manager, an object store client, a third-party SDK wrapper).

Unlike Database[T], the caller constructs the whole *T in build — so T can have arbitrary extra fields, not just an embedded manager — and returns an error to fail boot when the resource is required. The framework then:

  • manages lifecycle automatically: on boot it calls Start() if *T has one; on shutdown it calls Stop() (or Close()). Both void and error-returning forms are detected, so db/cache/queue managers (Start()/Stop()) and transport-style handles (Close() error) all work without the caller wiring hooks.

  • registers a dashboard resource via resourceFor (pass nil to skip — useful for a managed handle that isn't a topology node).

    type RabbitMQ struct { *rabbitmq.RabbitMQManager cfg *rabbitmq.RabbitMQConfig }

    nexus.Managed("rabbitmq", func(logger *slog.Logger) (*RabbitMQ, error) { cfg := rabbitmq.NewRabbitMQConfig() return &RabbitMQ{rabbitmq.NewRabbitMQManager(cfg, logger), cfg}, nil }, func(r *RabbitMQ) resource.Resource { return resource.NewQueue("rabbitmq", "RabbitMQ broker", map[string]any{"broker": "rabbitmq"}, r.IsConnected) }, )

Handlers inject *RabbitMQ unchanged. build receives the app's logger (App.Logger — the default JSON logger, or the one WithLogger installed).

func Middleware

func Middleware(entries ...any) Option

Middleware registers app-wide middleware: it runs on every request — REST, GraphQL, WebSocket upgrades, unmatched paths — ahead of any endpoint's own. Each entry is a middleware.Middleware, or a constructor returning one (optionally with an error) whose parameters come from DI like a provider's, so a middleware can depend on services:

var Middleware = nexus.Middleware(
    edge.Compress,      // middleware.Middleware with Stage: middleware.Edge
    admin.ThemeHead,    // func(doc *nexus.Document) middleware.Middleware
    auth.RequestedTarget,
)

Order comes from each middleware's Stage (Edge, Session, Auth, App), then from declaration order across the whole app — never from where a module happens to sit in Boot's list.

func Module

func Module(name string, opts ...Option) Option

Module groups options under a name. Mirrors di.Module's logging — the group name appears in startup/shutdown logs and in error messages, which helps when several modules touch the same service or resource. The name is also stamped onto every AsQuery/AsMutation/AsRest registration inside the module so the dashboard's architecture view can group endpoints by module container.

var ordersModule = nexus.Module("orders",
    nexus.Provide(NewOrdersService),
    nexus.AsQuery(NewListOrders),
    nexus.AsMutation(NewCreateOrder, …),
)

func MustLoadExtensions

func MustLoadExtensions(path ...string) Option

MustLoadExtensions is the panic-on-error variant matching config.MustLoad's idiom (Boot composes both for you; use this only for the explicit Run form). Use in main() when an extension block is required to boot.

func OnRouter

func OnRouter(name string, ops ...Option) Option

OnRouter attaches registrations to a declared router by name — generated by the `//nexus:on <name>` modifier. The ops mount under the router's stacked prefix with its shared options applied.

func Options

func Options(opts ...Option) Option

Options bundles multiple Option values into a single Option. Useful when one logical feature expands into several: a conditional gate that pulls in a frontend mount + a config supply + an extra invoke, for example. Empty input is a no-op.

func Provide

func Provide(fns ...any) Option

Provide registers one or more constructor functions with the dep graph and auto-detects two opt-in extensions:

  • Resource providers: any returned value implementing NexusResourceProvider has its resource.Resource list registered with the app at boot. Add UseReporter alongside and OnResourceUse wires automatically — service→resource edges appear on first UsingCtx call without manual plumbing.

  • Service wrappers: when the first return is a *T whose struct anonymously embeds *nexus.Service, the constructor's params are scanned for resource providers and other service wrappers. The resulting (resourceDeps, serviceDeps) lists are recorded on the service's registry entry so the dashboard's architecture view draws service→service and service→resource edges at the SERVICE layer with no extra annotation.

Constructors that don't trigger either detector behave like plain di.Provide — return types enter the graph, params resolve from it. Mixed sets (one service wrapper + one resource manager + one plain helper) work in a single call.

nexus.Provide(
    NewDBManager,        // resource provider — auto-registered
    NewCacheManager,     // ditto
    NewOrdersService,   // service wrapper — deps recorded
    NewClock,            // plain type — just enters the graph
)

func Raw

func Raw(opt di.Option) Option

Raw is an escape hatch: accept any di.Option and route it through nexus. For low-level container wiring or one-off integrations. Normal apps never need it.

nexus.Raw(di.Provide(myCtor))

func RouterDecl

func RouterDecl(name, prefix, parent string, shared ...MiddlewareOption) Option

RouterDecl declares a named router for decorator-form registration — generated by `//nexus:router <name> <prefix> [parent=<name>]` on a package doc comment. Hand-written code uses NewRouter instead. Declarations from every package are assembled into one tree when the app boots.

func Setup

func Setup(fns ...any) Option

Setup registers work that must finish before the app serves — migrations, roles, indexes, seeds, backfills:

nexus.Setup(EnsureReportRole, EnsureIndexes)

Each fn's parameters come from DI like a provider's, except a context.Context, which receives the boot context; it returns nothing or an error. Setup functions run after every resource and worker has started and before the listeners open, in declaration order; the first error stops boot, naming the function. They are listed in the deployment manifest as pre-start tasks.

func Supply

func Supply(values ...any) Option

Supply puts concrete values into the graph (no constructor). Useful for config structs or pre-built instances created outside the fx graph.

nexus.Supply(config.Runtime{Server: config.Server{Addr: ":8080"}})   // rare — Run takes config.Runtime directly
nexus.Supply(myAlreadyBuiltClient)          // typical

func WithContainer

func WithContainer(backend di.Backend) Option

WithContainer selects the dependency-injection backend (default: the zero-dependency builtin container in nexus/di). Pass the opt-in fx adapter to switch:

nexus.Boot(nexus.WithContainer(fxcontainer.New()))

Selecting the fx adapter pulls go.uber.org/fx (and dig) into the build; the builtin default links none of it. Mirrors WithRouter.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger replaces the app's logger (App.Logger and the *slog.Logger the framework provides into DI):

nexus.Boot(nexus.WithLogger(slog.New(myHandler)))

Any slog.Handler works. An app that prefers zap's encoder wraps a zap core in an slog.Handler (zap's own zapslog package does this) and passes the result here — the framework itself links no zap. Pass it once; providing a *slog.Logger by hand (nexus.Provide) collides with the framework's own.

func WithRouter

func WithRouter(r httpx.Router) Option

WithRouter selects the HTTP router backend (default: the zero-dependency stdlib net/http router). Pass an opt-in adapter to switch:

nexus.Boot(nexus.WithRouter(ginrouter.New()))
nexus.Run(cfg, nexus.WithRouter(chirouter.New()))

Equivalent to setting Config.Router. One line, no nexus.toml plumbing, and trivial to change — selecting gin/chi pulls their deps into the build, while the default links no third-party router at all.

type P added in v2.22.0

type P map[string]any

P fills path parameters by name in URL and Reverse.

type Params

type Params[T any] struct {
	Context context.Context
	Args    T
	Source  any
	// Info describes the GraphQL field being resolved (field name, parent
	// type, operation). Zero on other transports.
	Info gql.Info
	// Method is the HTTP verb for REST handlers ("GET", "POST", …). It lets
	// one handler registered for several methods (e.g. an Inertia page
	// mounted for GET+POST) branch on the verb. Empty for GraphQL / WS.
	Method string
}

Params is the bundle a reflective resolver receives when it wants more than just typed args — namely the resolve context, parent source, or schema info. Use it as the last parameter of an AsQuery / AsMutation handler (or AsRest, where only Context is filled).

func NewCreateOrder(
    svc *OrdersService,
    dbs *DBManager,
    cache *CacheManager,
    p nexus.Params[CreateOrderArgs],
) (*OrderResponse, error) {
    order := Order{Title: p.Args.Title, Total: p.Args.Total}
    return create(p.Context, order)
}

The type parameter T is the args struct — its fields carry the same `graphql:"..."` and `validate:"..."` tags as the legacy flat-args form. Use Params[struct{}] for resolvers that need Context/Source/Info but have no user-supplied args.

For simple handlers that only need a context.Context, you can still take that as a plain parameter; Params[T] is additive, not required.

type PathOpt

type PathOpt interface {
	Option
}

PathOpt is the static type Path returns. Satisfies Option so the value composes into a nexus.Module as a public-path prefix. Defined as a named interface so future Path behaviors can be added without breaking callers.

func Path

func Path(path string) PathOpt

Path sets the module's public URL path. Equivalent to declaring both nexus.RoutePrefix(path) on the module AND service.AtGraphQL(path+"/graphql") on the module's service — expressed once, kept in sync.

var Module = nexus.Module("billing",
    nexus.Path("/billing"),
    nexus.Provide(NewService),
    nexus.AsRest("POST", "/charge", NewCharge),
    nexus.AsQuery(NewListInvoices),
)

Effect: REST endpoints mount under /billing/* and GraphQL fields belonging to this module mount at /billing/graphql.

Why bother (vs a deployment-level prefix in the manifest): Path travels with the module — same URL in monolith and split deployments. The SPA's calls to /billing/graphql work in both shapes without conditional client logic.

Convention: the module name (first arg of nexus.Module) and the *Service name (passed to app.Service in the constructor) must match for the GraphQL path override to apply. Path looks up app.Service(name) by the module's name; if the service uses a different name, declare AtGraphQL explicitly for that service instead.

Leading slash is added if missing; trailing slash is trimmed.

The raw path is stored unchanged; module-side consumers normalize when reading (so "/" → "" for prefix purposes).

type PluginRecord

type PluginRecord struct {
	Name         string
	Version      string
	Icon         string     // lucide-style icon name; dashboard falls back to a default extension icon
	Namespace    string     // SDK accessor, "" if none
	HasDashboard bool       // declares Dashboard contribution
	HasClient    bool       // declares Client contribution
	Tab          *TabRecord // nav-tab metadata, nil if none
	LiveEvents   []string   // trace event names the plugin emits
}

PluginRecord is the inert metadata snapshot for a registered plugin. extension.Use builds one of these per Plugin and passes it to (*App).RegisterPlugin so the dashboard / introspection surfaces can list what's wired into the app without depending on the extension package directly.

type PublicOption

type PublicOption struct{}

PublicOption is the cross-transport carrier returned by Public — implements RestOption, GqlOption, and WSOption so one expression flows through any endpoint builder, mirroring AuthRouteOption / MiddlewareOption.

func Public

func Public() PublicOption

Public marks an endpoint as exempt from any framework-installed default gate — the explicit opt-out for deny-by-default auth (auth.Authorization.Default). With no default gate configured it's a harmless no-op marker. Works on REST (AsRest), GraphQL (AsQuery / AsMutation), and WS (AsWS):

nexus.AsRest("GET", "/health", NewHealth, nexus.Public())

Login endpoints marked nexus.AuthRoute("login") are auto-exempted (you can't require auth to obtain auth), so they need no Public().

type Query added in v2.22.0

type Query map[string]any

Query adds query parameters in URL and Reverse; a slice value repeats the parameter.

type RequestIdentityFunc

type RequestIdentityFunc func(ctx context.Context) (id string, ok bool)

RequestIdentityFunc reports the authenticated subject of a request from its context: the user id an identity provider resolved, and whether there was one. extension/auth registers one; an app with its own authentication can register another.

type RequestImpersonatorFunc added in v2.11.0

type RequestImpersonatorFunc func(ctx context.Context) (string, bool)

RequestImpersonatorFunc reports the real user behind a request that acts as another one (an impersonation).

type ResponseRenderer

type ResponseRenderer interface {
	Render(c *httpx.Ctx, result any) error
}

ResponseRenderer overrides how a REST endpoint's *successful* return value is written to the response. By default an AsRest handler's return is encoded with c.JSON(...); attaching a renderer via WithRenderer hands that final write to custom code instead.

This is the single extension point the Inertia integration (github.com/paulmanoni/nexus/v2/extension/inertia) builds on: a page handler stays an ordinary reflective handler returning a typed props struct, and the renderer wraps that struct into the Inertia page object — emitting JSON for XHR visits or an HTML document shell for full loads. Keeping the hook here (rather than re-implementing handler reflection in the extension) means params binding, validation, DI, tracing, and metrics behave identically to every other REST endpoint.

Render receives the live *httpx.Ctx (headers, request URL, the ResponseWriter) and the handler's return value. Returning an error is reported through gin.Context.Error and, if nothing has been written yet, produces a 500 — same as a handler error. Only successful returns reach a renderer; the error path is untouched.

type RestOption

type RestOption interface {
	// contains filtered or unexported methods
}

RestOption tunes an AsRest registration. Interface (not a func) so nexus.Use can satisfy both GqlOption and RestOption from a single value. The one-off func-shaped helpers below adapt via restOptionFn.

func ActionOption

func ActionOption(fn func(ctrl reflect.Type, action string) RestOption) RestOption

ActionOption is a REST option chosen by the controller action it is given to: fn receives the controller type and the action's method name. It is how an option names something after its action — inertia.AsPage() renders (*UsersController).Show as the page Users/Show:

nexus.Controller[*UsersController]("/users").
    Get("/:id", (*UsersController).Show, inertia.AsPage())

Outside a controller action (a plain AsRest) it fails the boot.

func DefaultName added in v2.22.0

func DefaultName(name string) RestOption

DefaultName replaces the name a route takes from its handler — for extensions that register routes on an app's behalf (view.Page names a page after its component, auth its endpoints "login", "me", …). Unlike Name it is a default: Name overrides it, and a clash with another route leaves the name ambiguous rather than failing the boot. DefaultName("") names the route after its namespace.

func Name added in v2.22.0

func Name(name string) RestOption

Name names a REST route, overriding the default — the handler's name with its first letter lowered ((*Users).Show → "show"). Names live in the namespace of the module the route is declared in, or of the router chain that includes it ("admin:users:show"); Name("") names the route after the namespace itself. Two routes given the same name explicitly fail the boot.

func NoActionDefaults

func NoActionDefaults() RestOption

NoActionDefaults exempts one action from its controller's ActionDefaults — a plain JSON endpoint on an Inertia resource, say.

func NoName added in v2.22.0

func NoName() RestOption

NoName keeps a route out of the names — for plumbing an extension registers (an upload endpoint, a socket) that nothing links to. Its handle still builds its URL.

func RestOptions

func RestOptions(opts ...RestOption) RestOption

RestOptions bundles several REST options into one, applied in order — for extensions whose single option expands to a renderer, tags and an icon (inertia.Component).

func WithRenderer

func WithRenderer(r ResponseRenderer) RestOption

WithRenderer attaches a ResponseRenderer to a single AsRest registration, replacing the default JSON success write. It is a REST-only option (GraphQL and WebSocket returns are encoded by their own transports).

nexus.AsRest("GET", "/users", NewListUsers, nexus.WithRenderer(myRenderer))

Most apps never call this directly — higher-level helpers such as inertia.Page wire the renderer for you.

type Route added in v2.22.0

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

Route is a REST registration — what AsRest (and inertia.Page, view.Live's page) returns. It is an Option, so it goes in a Module or Boot like any other, and a handle: once the app is running, URL builds the path it is served at, with the module's Path, the routers it sits in and the app's route_prefix applied.

var ShowUser = nexus.AsRest("GET", "/users/:id", (*Users).Show, nexus.Arg("id"))

ShowUser.URL(ctx, 7)        // "/api/users/7"

Every route is also reachable by name (see Name and URL).

func AsRest

func AsRest(method, path string, fn any, opts ...RestOption) *Route

AsRest registers a REST endpoint from a plain Go handler. The handler's signature is inspected via reflection:

  • Leading params are fx-injected deps. The first such param should be your service wrapper (see docs on Service) — its type grounds the endpoint in a service node on the dashboard.
  • The optional last param is an "args" struct whose tags direct gin on how to bind from the request: path:"id" → ShouldBindUri query:"x" → ShouldBindQuery header:"x" → ShouldBindHeader form:"x" → ShouldBind (multipart/url-encoded) json:"x" → ShouldBindJSON (for non-GET; default when other binders are absent)
  • The return may be (T, error), (T), (error), or nothing. T gets JSON-marshalled with status 200 (201 for POST) on success; errors render through the error model (see Error): the status of their code with {"code", "message", "errors"}. Args are validated (validate: tags) after binding; a failure is a 422 InvalidInput.

Returns an di.Option; drop it into di.Provide.

di.Provide(
    nexus.AsRest("GET", "/pets",     NewListPets),
    nexus.AsRest("POST", "/pets",    NewCreatePet),
    nexus.AsRest("GET", "/pets/:id", NewGetPet),
)

func FailRoute added in v2.22.0

func FailRoute(err error) *Route

FailRoute is a Route that fails the boot with err — for a constructor that returns a *Route and finds its arguments invalid.

func SameRoute added in v2.22.0

func SameRoute(first *Route, more ...*Route) *Route

SameRoute joins registrations of one route under several methods (a page served on GET and POST) into one handle; URL builds the first.

func (*Route) Method added in v2.22.0

func (r *Route) Method() string

Method is the route's HTTP method — for a form's method attribute.

func (*Route) Reverse added in v2.22.0

func (r *Route) Reverse(ctx context.Context, params ...any) (string, error)

Reverse is URL with the error returned. params fill the route's path parameters and query:

  • a scalar (string, number, bool, a fmt.Stringer, a pointer to one) fills the next path parameter, in the order they appear in the path;
  • P fills path parameters by name;
  • a struct (or pointer to one) fills them from its path:"x" fields and adds its non-zero query:"x" fields to the query — the handler's own args type works;
  • Query adds query parameters.

Id parameters are masked when extension/maskid is on, as responses are.

func (*Route) URL added in v2.22.0

func (r *Route) URL(ctx context.Context, params ...any) string

URL is the path the route is served at in the app serving ctx, with params filled in (see Reverse). A route that can't be built panics under nexus dev and in tests, and logs and returns "#" otherwise.

type RouteInfo added in v2.22.0

type RouteInfo struct {
	Name   string `json:"name"`
	Method string `json:"method"`
	Path   string `json:"path"`
}

RouteInfo is a named route: what nexus routes and App.Routes list.

type Router

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

Router is a FastAPI-style registration group: a first-class value that carries a URL prefix and shared per-op middleware, collects registrations, and nests. Each router becomes one dashboard module; including a router stacks prefixes and inherits the parent's shared options.

billing := nexus.NewRouter("billing", "/billing", auth.Required())
billing.Rest("GET", "/invoices", NewListInvoices)
billing.Query(NewInvoiceStats)

v1 := nexus.NewRouter("v1", "/api/v1")
v1.Include(billing) // billing mounts at /api/v1/billing

nexus.Boot(v1) // a *Router is an Option; pass only the root

Shared options are MiddlewareOptions (auth.Required, auth.Requires, session.Required, nexus.Use(...)): they apply to every REST, GraphQL and WebSocket registration in the router and in every included router, ahead of the op's own options. Workers and Provide are grouped but not gated.

func NewRouter

func NewRouter(name, prefix string, shared ...MiddlewareOption) *Router

NewRouter creates a router. name labels the dashboard module; prefix ("" or "/"-prefixed) prepends every route, stacking under Include.

func (*Router) Include

func (r *Router) Include(child *Router) *Router

Include nests child under r: the child's routes mount under r's prefix and inherit r's shared options (child's own shared options apply after). Pass only the ROOT router to Boot/Run — an included router used directly errors.

func (*Router) Mutation

func (r *Router) Mutation(fn any, opts ...GqlOption) *Router

Mutation registers a GraphQL mutation on the router.

func (*Router) Provide

func (r *Router) Provide(fns ...any) *Router

Provide adds constructors under the router's module.

func (*Router) Query

func (r *Router) Query(fn any, opts ...GqlOption) *Router

Query registers a GraphQL query on the router.

func (*Router) Register

func (r *Router) Register(opts ...Option) *Router

Register adds arbitrary options under the router's module, ungated.

func (*Router) Rest

func (r *Router) Rest(method, path string, fn any, opts ...RestOption) *Router

Rest registers a REST endpoint on the router.

func (*Router) Reverse added in v2.22.0

func (r *Router) Reverse(ctx context.Context, name string, params ...any) (string, error)

Reverse is Router.URL with the error returned.

func (*Router) Subscription

func (r *Router) Subscription(fn any, opts ...GqlOption) *Router

Subscription registers a GraphQL subscription on the router.

func (*Router) URL added in v2.22.0

func (r *Router) URL(ctx context.Context, name string, params ...any) string

URL builds the URL of the route named name in r's namespace.

func (*Router) WS

func (r *Router) WS(path, msgType string, fn any, opts ...WSOption) *Router

WS registers a WebSocket message handler on the router.

func (*Router) Worker

func (r *Router) Worker(name string, fn any) *Router

Worker registers a background worker under the router's module (workers serve no requests, so shared middleware does not apply).

type Scoped

type Scoped[T any] struct {
	// contains filtered or unexported fields
}

Scoped is the typed handle NewScoped returns — the only door to the value, so a fact nobody registered cannot be asked for by accident.

func NewScoped

func NewScoped[T any](ctor any) *Scoped[T]

NewScoped declares a REQUEST-SCOPED derived value: a fact computed from the request (identity + DB, tenant state, a feature evaluation) at most once per request, on first ask, and shared by every handler, service and prop that asks after. The ctor's params are DI-injected; its single return is the Compute:

var delegatedScope = nexus.NewScoped[Scope](func(svc *services.UserMgmtService) nexus.Compute[Scope] {
    return func(ctx context.Context) (Scope, error) {
        id, restricted := svc.DelegatedHrScope(ctx)
        return Scope{EmployerID: id, Restricted: restricted}, nil
    }
})

nexus.Boot(delegatedScope, ...)          // the handle is an Option

scope, err := delegatedScope.Get(ctx)    // anywhere, any transport

Semantics — deliberately narrow:

  • Lazy: a request whose handlers never Get pays only the (pooled) store install; apps with no Scoped registered pay nothing at all.
  • Once per request: concurrent Gets (GraphQL resolvers) share one compute; the ERROR memoizes too, so a failed derivation is one consistent answer for the whole request, not N retries.
  • Per-request only: no TTL, no cross-request cache, no invalidation. A fact that tolerates staleness belongs on the identity (resolve- time enrichment rides the auth cache); a fact that outlives requests belongs in extension/cache. One lifetime keeps the model exact.

The handle also AUTO-PROVIDES itself into the DI graph, so a handler can declare the fact it reads as an ordinary dep instead of touching the package var: `func NewUsersPage(ctx context.Context, scope *nexus.Scoped[Scope], ...)`. Distinct fact types are distinct DI slots (*Scoped[A] and *Scoped[B] coexist); TWO handles of the SAME T in one app trip the container's duplicate-provider boot error — mark the extras .NoProvide(), or give each fact its own named type.

A handle binds to ONE app at a time (the package-level-var + single-app pattern; a later boot rebinds it). Do not Get the same handle from inside its own Compute — that self-wait deadlocks the slot. In unit tests, inject a value with nexus.WithScopedValue instead of booting. (T is spelled explicitly — the ctor is `any` so Go cannot infer it.)

func (*Scoped[T]) Get

func (s *Scoped[T]) Get(ctx context.Context) (T, error)

Get returns the request's value, computing it on the first ask. Callable from any depth — the store rides the request context every transport already carries.

func (*Scoped[T]) NoProvide

func (s *Scoped[T]) NoProvide() *Scoped[T]

NoProvide disables the handle's DI auto-provide. Needed only when ONE app registers TWO handles of the same T — the DI container is type-addressed, so the second *Scoped[T] provider is a boot error ("provided more than once"); mark all but one NoProvide, or better, give each fact its own named type. Chainable at var init:

var apiScope = nexus.NewScoped[Scope](...).NoProvide()

type Service

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

Service is a named group of endpoints. Services are the nodes the dashboard draws in the architecture view.

A Service also carries the GraphQL mount path for reflective controllers registered via nexus.AsQuery / AsMutation. The auto-mount step inside fxmod.Module reads this path at fx.Start and wires the schema onto the engine. Default is "/graphql"; override via (*Service).AtGraphQL.

func (*Service) AtGraphQL

func (s *Service) AtGraphQL(path string) *Service

AtGraphQL overrides the GraphQL mount path for this service. Most apps keep the default ("/graphql") — override only when you need a per-service path (e.g. "/admin/graphql") or want to unify multiple nexus apps behind the same reverse proxy.

app.Service("admin").AtGraphQL("/admin/graphql").Describe("Admin ops")

func (*Service) Attach

func (s *Service) Attach(r resource.Resource) *Service

Attach links a resource to this service so the dashboard draws an edge. If the resource isn't already registered, Attach registers it too — that's convenient for ad-hoc services but means typos silently create orphan nodes. For centrally-declared resources, prefer .Using("name") instead.

func (*Service) Auth

func (s *Service) Auth(fn UserDetailsFn) *Service

Auth wires a Bearer-token → user hook for this service's GraphQL endpoint. The context fn returns becomes the resolvers' context, so put the user there (or use extension/auth, which works on every transport). Per-service because different services often use different auth mechanisms (admin vs public).

func (*Service) Describe

func (s *Service) Describe(desc string) *Service

func (*Service) GraphQLPath

func (s *Service) GraphQLPath() string

GraphQLPath returns the mount path set via AtGraphQL (or the default). Read by the auto-mount Invoke; users rarely need this.

func (*Service) Name

func (s *Service) Name() string

Name returns the service's identifier (same string used on the dashboard and passed to *App.Service). Exposed so framework internals (the auto- mount Invoke, service wrappers) can identify a service without reaching into the private field.

func (*Service) REST

func (s *Service) REST(method, path string) *rest.Builder

func (*Service) Using

func (s *Service) Using(names ...string) *Service

Using attaches already-registered resources by name so the dashboard draws edges. An empty string resolves to the default database (the resource of kind Database marked resource.AsDefault(), or the lexically-first if none is marked). Unknown names are attached anyway so the registry shows a disconnected edge — surfacing the typo rather than hiding it.

app.Service("orders").Using("")                 // default DB
app.Service("quiz").Using("questions", "session") // explicit

func (*Service) UsingDefaults

func (s *Service) UsingDefaults() *Service

UsingDefaults attaches the default resource of every kind that has at least one registered (database, cache, queue). Useful for services that touch the common "main DB + session cache" pair without naming either.

func (*Service) WebSocket

func (s *Service) WebSocket(path string) *ws.Builder

type SharedPagePropFunc added in v2.3.0

type SharedPagePropFunc func(ctx context.Context) (key string, value any)

SharedPagePropFunc contributes one prop to every server-rendered page — key "" to skip this request.

func SharedPageProps added in v2.3.0

func SharedPageProps() []SharedPagePropFunc

SharedPageProps returns the registered shared page props, for renderers.

type TabRecord

type TabRecord struct {
	ID    string
	Label string
	Icon  string
}

TabRecord is the dashboard nav-tab metadata declared by a plugin.

type TagOption

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

TagOption is the cross-transport carrier returned by Tag — implements RestOption, GqlOption, and WSOption so one expression flows through any endpoint builder, mirroring IconOption.

func Tag

func Tag(key, value string) TagOption

Tag stamps one key/value pair onto an endpoint's registry tags — the metadata channel the dashboard, the client SDK manifest, and codegen read. It is the exported form of what WithIcon / HideFromDashboard / AuthRoute do internally, so an extension can mark the endpoints it registers without a dedicated option in this package:

// extension/inertia: mark a route as a page for the SDK's NexusPageProps
nexus.AsRest("GET", path, fn, nexus.Tag(registry.PageTag, component))

Cross-transport (REST / GraphQL / WS). Keys are namespaced by convention ("<owner>.<name>", e.g. "inertia.page"); a later Tag with the same key replaces the earlier value. An empty key is ignored.

The keys this package's own options own are refused (Tag panics at registration, naming the option): some of them are not just metadata — auth.public and auth.flow exempt a route from the deny-by-default gate, and an auth.requires that disagrees with the middleware would make auth.OpGates report an op the endpoint refuses. Use Public, AuthRoute, auth.Requires, HideFromDashboard, WithIcon or Envelope for those.

type UseReporter

type UseReporter interface {
	OnUse(func(ctx context.Context, name string))
}

UseReporter is satisfied by any type that exposes an OnUse hook with this exact signature — typically a registry routing several named instances (databases, clients) that reports which one each call used.

type UserDetailsFn

type UserDetailsFn func(ctx context.Context, token string) (context.Context, any, error)

UserDetailsFn, when set on a service, is called with the GraphQL request's Bearer token; the context it returns is the one resolvers see. The returned details value is available to the engine's validation rules, not to handlers.

type UserError

type UserError struct {
	Op    string   // short verb-noun: "topology", "remote call", "path expand"
	Msg   string   // primary one-line description
	Notes []string // optional context lines (peer list, body snippet, etc.)
	Hint  string   // optional fix recipe; single line
	Cause error    // optional wrap — accessible via errors.Unwrap
}

UserError is the framework's developer-facing error envelope. Fields produce a multi-line format with an optional `hint:` recipe and an optional `cause:` wrap so a developer hitting a framework error sees what went wrong, what to do about it, and the underlying cause in one block — instead of having to chase the message through several fmt.Errorf wraps.

nexus error [topology]: Deployment "users-svc" not in Topology.Peers
  declared peers: [checkout-svc orders-svc]
  hint: add Topology.Peers["users-svc"] in main.go's config.Runtime — URL may be empty for the active unit

User code typically doesn't construct these — the framework emits them at known failure boundaries. They behave like normal errors (Error / Unwrap), so existing error-handling paths work unchanged.

func (*UserError) Error

func (e *UserError) Error() string

func (*UserError) Unwrap

func (e *UserError) Unwrap() error

type WSCarrier

type WSCarrier func(upgrade, conn context.Context) context.Context

WSCarrier copies values from a WebSocket upgrade request's context onto a connection's base context and returns it. Each message handler's context (Params.Context, WSSession.Context) derives from that base, so what a carrier copies — extension/auth copies the identity and its own state — is what auth.IdentityFrom, auth.Can and the like see in a WS handler.

type WSOption

type WSOption interface {
	// contains filtered or unexported methods
}

WSOption tunes an AsWS registration. Interface (not a func) so nexus.Use and auth.Required() — which return middleware bundles — can satisfy both RestOption and WSOption from a single value.

func ClientRooms

func ClientRooms(allow func(userID, room string) bool) WSOption

ClientRooms lets clients on this WebSocket path join rooms themselves with the built-in {"type":"subscribe","room":"…"} message, for the rooms allow accepts. userID is the connection's authenticated user ("" when anonymous). Without it every client subscribe is refused: a room is an audience the server addresses with EmitToRoom, so by default only a handler joins one (WSSession.JoinRoom), after checking the caller. The hub is shared by every AsWS on the path; the last ClientRooms given for the path applies.

nexus.AsWS("/ws", "jobs.watch", NewWatch, auth.Required(),
    nexus.ClientRooms(func(userID, room string) bool { return room == "jobs" && userID != "" }))

type WSSession

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

WSSession is the per-connection handle injected into AsWS handlers. Every handler that declares `*nexus.WSSession` as a parameter receives the session tied to the connection that produced the current inbound message. Safe for concurrent use — wraps a ws.Hub under the hood.

The framework uses the same envelope protocol as the built-in ws.Hub:

{ "type": "chat.send", "data": {...}, "timestamp": <unix> }

Emit / EmitToUser / EmitToRoom / EmitToClient publish in that shape; SendRaw is the escape hatch for non-envelope payloads.

func (*WSSession) ClientID

func (s *WSSession) ClientID() string

ClientID is the UUID the hub minted for this connection at upgrade time.

func (*WSSession) Context

func (s *WSSession) Context() context.Context

Context returns a context cancelled when the connection disconnects. Safe to pass downstream — long-running work will unblock on hangup.

func (*WSSession) Emit

func (s *WSSession) Emit(eventType string, data any)

Emit broadcasts an envelope to every connection on this endpoint.

func (*WSSession) EmitToClient

func (s *WSSession) EmitToClient(eventType string, data any, clientIDs ...string)

EmitToClient sends an envelope to the connections with the given IDs.

func (*WSSession) EmitToRoom

func (s *WSSession) EmitToRoom(eventType string, data any, room string)

EmitToRoom sends an envelope to every connection subscribed to room.

func (*WSSession) EmitToUser

func (s *WSSession) EmitToUser(eventType string, data any, userIDs ...string)

EmitToUser sends an envelope to every connection authed as one of userIDs.

func (*WSSession) JoinRoom

func (s *WSSession) JoinRoom(room string)

JoinRoom subscribes this connection to a room. The server's way to put a connection in an audience, after the handler has checked the caller may hear it; a client's own `{"type":"subscribe"}` is refused unless the path allows it with ClientRooms.

func (*WSSession) LeaveRoom

func (s *WSSession) LeaveRoom(room string)

LeaveRoom unsubscribes this connection from a room.

func (*WSSession) Metadata

func (s *WSSession) Metadata() map[string]any

Metadata is the map the hub's identify hook populated at upgrade time. Read freely; mutation is not safe across goroutines.

func (*WSSession) Send

func (s *WSSession) Send(eventType string, data any) error

Send wraps data in an envelope and unicasts it to this connection.

func (*WSSession) SendRaw

func (s *WSSession) SendRaw(data []byte)

SendRaw writes bytes directly to this connection with no envelope. Use when you're speaking a non-nexus protocol (e.g. pre-marshalled binary data).

func (*WSSession) UserID

func (s *WSSession) UserID() string

UserID is the identity attached at upgrade (via `?userId=` query or a gin-context `user` interface) or later via the client-initiated `authenticate` protocol message. Empty when the connection is unauthed.

Directories

Path Synopsis
Package client embeds and serves the nexus client SDK — a JS/TS runtime, generated TypeScript types, and Vue 3 composables — directly from the Go binary.
Package client embeds and serves the nexus client SDK — a JS/TS runtime, generated TypeScript types, and Vue 3 composables — directly from the Go binary.
Package dataloader coalesces N individual key lookups into one batched fetch, eliminating the N+1 query pattern that GraphQL's nested resolvers otherwise produce.
Package dataloader coalesces N individual key lookups into one batched fetch, eliminating the N+1 query pattern that GraphQL's nested resolvers otherwise produce.
db
Package db is nexus's driver-agnostic GORM manager.
Package db is nexus's driver-agnostic GORM manager.
mysql
Package mysql links gorm's MySQL driver into nexus/db.
Package mysql links gorm's MySQL driver into nexus/db.
postgres
Package postgres links gorm's Postgres driver (pgx) into nexus/db.
Package postgres links gorm's Postgres driver (pgx) into nexus/db.
sqlite
Package sqlite links the pure-Go SQLite engine (glebarez/modernc) into nexus/db.
Package sqlite links the pure-Go SQLite engine (glebarez/modernc) into nexus/db.
Package decorate is the runtime side of nexus's //nexus:-annotation system.
Package decorate is the runtime side of nexus's //nexus:-annotation system.
Package dev is what an app sees of `nexus dev`: whether it runs under it, and the state it can carry across the rebuilds the dev loop makes.
Package dev is what an app sees of `nexus dev`: whether it runs under it, and the state it can carry across the rebuilds the dev loop makes.
di
Package di is nexus's built-in dependency-injection container: a small, zero-third-party-dependency replacement for the subset of go.uber.org/fx that the framework actually uses.
Package di is nexus's built-in dependency-injection container: a small, zero-third-party-dependency replacement for the subset of go.uber.org/fx that the framework actually uses.
ditest
Package ditest provides a backend-agnostic conformance suite for the di seam.
Package ditest provides a backend-agnostic conformance suite for the di seam.
examples
bigtopo command
Command bigtopo is a synthetic large-topology app for stress-testing the dashboard's architecture graph (drill-down, edge bundling, level-of-detail, layout/perf) at ~1000 nodes — far beyond what the small examples produce.
Command bigtopo is a synthetic large-topology app for stress-testing the dashboard's architecture graph (drill-down, edge bundling, level-of-detail, layout/perf) at ~1000 nodes — far beyond what the small examples produce.
fxapp command
An example showing nexus's top-level builder: nexus.Run composes modules, nexus.Provide / Invoke / Module replace fx.Provide / Invoke / Module — no go.uber.org/fx import in user code.
An example showing nexus's top-level builder: nexus.Run composes modules, nexus.Provide / Invoke / Module replace fx.Provide / Invoke / Module — no go.uber.org/fx import in user code.
graphapp command
Example: a complete GraphQL service wired with nexus's reflective controller API.
Example: a complete GraphQL service wired with nexus's reflective controller API.
inertia command
Command inertia is a small, runnable Inertia app: a Vue client under web/ driven by Go page handlers registered with the //nexus:inertia.Page custom decorator (see ./pages).
Command inertia is a small, runnable Inertia app: a Vue client under web/ driven by Go page handlers registered with the //nexus:inertia.Page custom decorator (see ./pages).
inertia/pages
Package pages holds the Inertia page handlers, registered via the //nexus:inertia.Page custom decorator — the codegen emits decorate.Record(inertia.Page("GET", "/users", "Users/Index", NewUsers)), reusing the extension's existing Option-returning registrar with no wrapper.
Package pages holds the Inertia page handlers, registered via the //nexus:inertia.Page custom decorator — the codegen emits decorate.Record(inertia.Page("GET", "/users", "Users/Index", NewUsers)), reusing the extension's existing Option-returning registrar with no wrapper.
notes command
Command notes is a small, real app showing decorator-form registration (//nexus:provide / //nexus:rest / //nexus:query in the notes package) coexisting with an explicit hand-written endpoint — all on one DI container and one dashboard.
Command notes is a small, real app showing decorator-form registration (//nexus:provide / //nexus:rest / //nexus:query in the notes package) coexisting with an explicit hand-written endpoint — all on one DI container and one dashboard.
notes/widgets
Package widgets is a stand-in for an extension (think inertia) that ships its OWN decorator.
Package widgets is a stand-in for an extension (think inertia) that ships its OWN decorator.
petstore command
petstore-spa command
pubsub command
Demonstrates nexus's typed pub/sub primitive end-to-end:
Demonstrates nexus's typed pub/sub primitive end-to-end:
wsecho command
Command wsecho is a runnable demo of nexus.AsWS: one WebSocket path (/events) with two typed message handlers (chat.send + chat.typing) sharing one connection pool.
Command wsecho is a runnable demo of nexus.AsWS: one WebSocket path (/events) with two typed message handlers (chat.send + chat.typing) sharing one connection pool.
wstest command
Package extension is the plugin seam for nexus.
Package extension is the plugin seam for nexus.
auth
Package auth is nexus's authentication and authorization: accounts the app describes with one interface, credentials nexus issues and checks (sessions, bearer tokens, API keys, JWTs from elsewhere), sign-in flows, and gates that work the same on REST, GraphQL, WebSocket, Inertia pages and views.
Package auth is nexus's authentication and authorization: accounts the app describes with one interface, credentials nexus issues and checks (sessions, bearer tokens, API keys, JWTs from elsewhere), sign-in flows, and gates that work the same on REST, GraphQL, WebSocket, Inertia pages and views.
auth/authdb
Package authdb keeps extension/auth's issued tokens, API keys and session records in a SQL database — restart-safe and shared by every replica, without a cache.
Package authdb keeps extension/auth's issued tokens, API keys and session records in a SQL database — restart-safe and shared by every replica, without a cache.
auth/authtest
Package authtest helps tests of apps using extension/auth: requests authenticated as anyone, and an in-memory Users.
Package authtest helps tests of apps using extension/auth: requests authenticated as anyone, and an in-memory Users.
cache
Package cache provides a cache for nexus apps.
Package cache provides a cache for nexus apps.
cache/cacheconfig
Package cacheconfig declares the [cache.<name>] tables of nexus.toml.
Package cacheconfig declares the [cache.<name>] tables of nexus.toml.
config
Package config wires Spring-Cloud-Config-style configuration distribution into a nexus mesh.
Package config wires Spring-Cloud-Config-style configuration distribution into a nexus mesh.
config/internal/canonical
Package canonical emits RFC 8785-style canonical JSON so two servers producing the same value tree produce byte-identical signing inputs.
Package canonical emits RFC 8785-style canonical JSON so two servers producing the same value tree produce byte-identical signing inputs.
cors
Package cors implements CORS (Cross-Origin Resource Sharing) for nexus apps.
Package cors implements CORS (Cross-Origin Resource Sharing) for nexus apps.
cron
Package cron registers and runs scheduled jobs alongside the app's HTTP surface.
Package cron registers and runs scheduled jobs alongside the app's HTTP surface.
dashboard
templ: version: v0.3.1020
templ: version: v0.3.1020
dashboard/internal/ui/badge
templ: version: v0.3.1020
templ: version: v0.3.1020
dashboard/internal/ui/button
templ: version: v0.3.1020
templ: version: v0.3.1020
dashboard/internal/ui/card
templ: version: v0.3.1020
templ: version: v0.3.1020
dashboard/internal/ui/icon
Package icon renders the handful of Lucide icons (ISC licensed, lucide.dev) the dashboard uses.
Package icon renders the handful of Lucide icons (ISC licensed, lucide.dev) the dashboard uses.
dashboard/internal/ui/input
templ: version: v0.3.1020
templ: version: v0.3.1020
dashboard/internal/ui/table
templ: version: v0.3.1020
templ: version: v0.3.1020
dashboard/internal/ui/utils
Package utils is the slice of templUI's utils the vendored components use.
Package utils is the slice of templUI's utils the vendored components use.
errors
Package errors captures unhandled panics and 5xx-shaped failures from a nexus app, deduplicates them by fingerprint, surfaces the rolling history on the dashboard, and forwards each new occurrence to one or more configured transports (Sentry, generic webhook, stdout).
Package errors captures unhandled panics and 5xx-shaped failures from a nexus app, deduplicates them by fingerprint, surfaces the rolling history on the dashboard, and forwards each new occurrence to one or more configured transports (Sentry, generic webhook, stdout).
frontend
Package frontend wires a single-page-app bundle into a nexus app as a first-class plugin.
Package frontend wires a single-page-app bundle into a nexus app as a first-class plugin.
inertia
Package inertia adds Inertia.js (https://inertiajs.com) support to nexus: server-driven pages that return a typed props struct instead of building a client-side API.
Package inertia adds Inertia.js (https://inertiajs.com) support to nexus: server-driven pages that return a typed props struct instead of building a client-side API.
inertia/inertiatest
Package inertiatest is the in-process testing harness for Inertia pages — the Inertia-aware layer over nexustest.
Package inertiatest is the in-process testing harness for Inertia pages — the Inertia-aware layer over nexustest.
inertia/ssrhttp
Package ssrhttp is the default Inertia SSRRenderer: it POSTs the page object to a Node SSR server and decodes the {head, body} response — the @inertiajs/server protocol.
Package ssrhttp is the default Inertia SSRRenderer: it POSTs the page object to a Node SSR server and decodes the {head, body} response — the @inertiajs/server protocol.
jobs
Package jobs runs background work — jobs — outside the request that asks for it: queued, retried, cancellable, with progress a page can show.
Package jobs runs background work — jobs — outside the request that asks for it: queued, retried, cancellable, with progress a page can show.
jobs/jobsdb
Package jobsdb stores background jobs in a SQL database — the "db" driver of extension/jobs.
Package jobsdb stores background jobs in a SQL database — the "db" driver of extension/jobs.
mail
Package mail is nexus's outbound email abstraction — the Go equivalent of Laravel's Mail / Rails ActionMailer / Django's email backends.
Package mail is nexus's outbound email abstraction — the Go equivalent of Laravel's Mail / Rails ActionMailer / Django's email backends.
maskid
Package maskid replaces sequential integer IDs with opaque strings on the wire, without changing handler code.
Package maskid replaces sequential integer IDs with opaque strings on the wire, without changing handler code.
metrics
Package metrics records per-endpoint request counts + errors so the dashboard can show at-a-glance health next to each op: how busy it is, whether it's failing, and if so, what the last error was.
Package metrics records per-endpoint request counts + errors so the dashboard can show at-a-glance health next to each op: how busy it is, whether it's failing, and if so, what the last error was.
openapi
Package openapi auto-generates an OpenAPI 3.1 specification from the framework's typed registry and serves it (plus Swagger UI) from a nexus app.
Package openapi auto-generates an OpenAPI 3.1 specification from the framework's typed registry and serves it (plus Swagger UI) from a nexus app.
peer
Package peer wires typed RPC between nexus apps.
Package peer wires typed RPC between nexus apps.
proxy
Package proxy is a strangler-fig bridge: it reverse-proxies routes to a legacy upstream (e.g.
Package proxy is a strangler-fig bridge: it reverse-proxies routes to a legacy upstream (e.g.
ratelimit
Package ratelimit provides the rate-limit primitives nexus uses to throttle endpoints: a Limit shape, a Store interface (pluggable to memory, Redis, or any backend), and a token-bucket MemoryStore.
Package ratelimit provides the rate-limit primitives nexus uses to throttle endpoints: a Limit shape, a Store interface (pluggable to memory, Redis, or any backend), and a token-bucket MemoryStore.
security
Package security is the dashboard + per-route surface for nexus's two web-security defenses — security response headers and CSRF.
Package security is the dashboard + per-route surface for nexus's two web-security defenses — security response headers and CSRF.
session
Package session gives nexus Django-style server-side sessions: a cookie carries an opaque session ID, the data lives in a pluggable Store, and handlers read and write it through a lazy per-request handle — for anonymous visitors and logged-in users alike.
Package session gives nexus Django-style server-side sessions: a cookie carries an opaque session ID, the data lives in a pluggable Store, and handlers read and write it through a lazy per-request handle — for anonymous visitors and logged-in users alike.
storage
Package storage is nexus's file/object storage abstraction — the Go equivalent of Laravel's Storage / Rails ActiveStorage / Django's file storages.
Package storage is nexus's file/object storage abstraction — the Go equivalent of Laravel's Storage / Rails ActiveStorage / Django's file storages.
tls
Package tls auto-acquires and renews Let's Encrypt TLS certificates for a nexus app, terminating HTTPS in-process — no nginx, certbot, or external reverse proxy needed.
Package tls auto-acquires and renews Let's Encrypt TLS certificates for a nexus app, terminating HTTPS in-process — no nginx, certbot, or external reverse proxy needed.
frontend
vitehot
Package vitehot reads the file nexus-vite-plugin writes while `vite dev` runs.
Package vitehot reads the file nexus-vite-plugin writes while `vite dev` runs.
vitemanifest
Package vitemanifest reads the manifest `vite build` writes — the prod half of the frontend contract, as internal/vitehot is the dev half.
Package vitemanifest reads the manifest `vite build` writes — the prod half of the frontend contract, as internal/vitehot is the dev half.
Package gql holds the types nexus's GraphQL surface is written in.
Package gql holds the types nexus's GraphQL surface is written in.
Package httpx is nexus's router-agnostic HTTP seam.
Package httpx is nexus's router-agnostic HTTP seam.
chirouter
Package chirouter is an opt-in chi-backed nexus router.
Package chirouter is an opt-in chi-backed nexus router.
routertest
Package routertest provides a backend-agnostic conformance suite for the httpx.Router seam.
Package routertest provides a backend-agnostic conformance suite for the httpx.Router seam.
stdrouter
Package stdrouter is the DEFAULT nexus router: Go 1.22's net/http.ServeMux behind the httpx.Router seam, with zero third-party dependencies.
Package stdrouter is the DEFAULT nexus router: Go 1.22's net/http.ServeMux behind the httpx.Router seam, with zero third-party dependencies.
internal
appctx
Package appctx holds the request-context key under which nexus stashes the *App for code that runs inside a request but can't have the app threaded through its signature — a ResponseRenderer, an extension's dashboard route.
Package appctx holds the request-context key under which nexus stashes the *App for code that runs inside a request but can't have the app threaded through its signature — a ResponseRenderer, an extension's dashboard route.
bindutil
Package bindutil holds the mechanics every typed resource binder (db.Bind, cache.Bind, mail.Bind, storage.Bind) shares: discovering the embedded manager field on the marker type, constructing the holder, and the dashboard-registration option set.
Package bindutil holds the mechanics every typed resource binder (db.Bind, cache.Bind, mail.Bind, storage.Bind) shares: discovering the embedded manager field on the marker type, constructing the holder, and the dashboard-registration option set.
bootui
Package bootui prints the diagnostic block a failed boot exits with: a config error with its file, line and fix, or any other startup error.
Package bootui prints the diagnostic block a failed boot exits with: a config error with its file, line and fix, or any other startup error.
dotpath
Package dotpath splits dotted config keys ("runtime.server.addr") without strings.Split's intermediate allocations.
Package dotpath splits dotted config keys ("runtime.server.addr") without strings.Split's intermediate allocations.
extnames
Package extnames records which [extensions.*] names have a decoder registered in this binary.
Package extnames records which [extensions.*] names have a decoder registered in this binary.
golden
Package golden is a tiny golden-file helper for the framework's code generators (client SDK, decorator codegen, schema walk).
Package golden is a tiny golden-file helper for the framework's code generators (client SDK, decorator codegen, schema walk).
gqlhttp
Package gql mounts a GraphQL schema (typically assembled by github.com/paulmanoni/nexus/v2/graph) onto the router and introspects its operations into the nexus registry.
Package gql mounts a GraphQL schema (typically assembled by github.com/paulmanoni/nexus/v2/graph) onto the router and introspects its operations into the nexus registry.
graph
Package graph provides a modern, secure GraphQL handler for Go with built-in authentication, validation, and an intuitive builder API.
Package graph provides a modern, secure GraphQL handler for Go with built-in authentication, validation, and an intuitive builder API.
maskhook
Package maskhook is the framework-side seam for opaque ID masking.
Package maskhook is the framework-side seam for opaque ID masking.
staticfs
Package staticfs is the file system the routers' Static serves: a directory only through its index.html, never as a listing of what it holds — the behaviour gin's Static already had.
Package staticfs is the file system the routers' Static serves: a directory only through its index.html, never as a listing of what it holds — the behaviour gin's Static already had.
tsgen
Package tsgen renders registry schema shapes as TypeScript source.
Package tsgen renders registry schema shapes as TypeScript source.
Package manifest is the deploy-time self-description surface for a nexus app.
Package manifest is the deploy-time self-description surface for a nexus app.
Package middleware defines nexus's cross-transport middleware model.
Package middleware defines nexus's cross-transport middleware model.
secure
Package secure holds the transport-neutral implementations of the two web-security defenses nexus applies — security response headers and CSRF — with no dependency beyond httpx and the standard library.
Package secure holds the transport-neutral implementations of the two web-security defenses nexus applies — security response headers and CSRF — with no dependency beyond httpx and the standard library.
Package nexustest is the in-process testing harness for nexus apps — the framework's own net/http/httptest.
Package nexustest is the in-process testing harness for nexus apps — the framework's own net/http/httptest.
Package pubsub is nexus's typed pub/sub primitive.
Package pubsub is nexus's typed pub/sub primitive.
rabbit
Package rabbit is the production RabbitMQ adapter for nexus's pubsub primitive.
Package rabbit is the production RabbitMQ adapter for nexus's pubsub primitive.
Package registry stores metadata about every endpoint a nexus app exposes.
Package registry stores metadata about every endpoint a nexus app exposes.
Package resource defines the abstractions nexus uses to know about databases, caches, message queues, and other external dependencies so they show up in the dashboard's Architecture view with health status.
Package resource defines the abstractions nexus uses to know about databases, caches, message queues, and other external dependencies so they show up in the dashboard's Architecture view with health status.
connlog
Package logx holds the log-shaping helpers the resource managers share: collapsing a failure that recurs on a retry tick, and turning a bare network error into a line the reader can act on.
Package logx holds the log-shaping helpers the resource managers share: collapsing a failure that recurs on a retry tick, and turning a bare network error into a line the reader can act on.
Package trace captures request-lifecycle events (start, end, downstream calls, logs) into an in-memory ring buffer and fans them out to subscribers such as the dashboard.
Package trace captures request-lifecycle events (start, end, downstream calls, logs) into an in-memory ring buffer and fans them out to subscribers such as the dashboard.
otlp
Package otlp exports nexus traces to an OpenTelemetry collector over OTLP/HTTP (JSON).
Package otlp exports nexus traces to an OpenTelemetry collector over OTLP/HTTP (JSON).
transport
rest
Package rest wires REST endpoints onto the router and records metadata about them in the nexus registry.
Package rest wires REST endpoints onto the router and records metadata about them in the nexus registry.
ws
Package ws wires WebSocket endpoints onto the router using gorilla/websocket and records metadata about them in the nexus registry.
Package ws wires WebSocket endpoints onto the router using gorilla/websocket and records metadata about them in the nexus registry.
Package view renders templ components from nexus handlers and makes them reactive without a JavaScript build.
Package view renders templ components from nexus handlers and makes them reactive without a JavaScript build.
internal/browser
Package browser runs the view runtime against a small DOM in goja: a page realm with documents, events, form fields, selectors, a virtual clock, fetch and WebSocket, whose network is supplied by the host.
Package browser runs the view runtime against a small DOM in goja: a page realm with documents, events, form fields, selectors, a virtual clock, fetch and WebSocket, whose network is supplied by the host.
ui
templ: version: v0.3.1020
templ: version: v0.3.1020
viewgen
Package rewrite compiles reactive .templ files.
Package rewrite compiles reactive .templ files.
viewgen/cmd/instrument command
Command instrument records live render trees in templ output that wasn't compiled by nexus (templ generate): it rewrites each *_templ.go under the given directories with viewgen.Instrument, as nexus's view compiler does.
Command instrument records live render trees in templ output that wasn't compiled by nexus (templ generate): it rewrites each *_templ.go under the given directories with viewgen.Instrument, as nexus's view compiler does.
viewgen/jsgen
Package jsgen compiles the Go expressions of a reactive templ attribute to JavaScript.
Package jsgen compiles the Go expressions of a reactive templ attribute to JavaScript.
viewtest
Package viewtest drives view pages end to end in a test, without a browser: the page is fetched over HTTP from the app, the view runtime (/_view/runtime.js and the compiled expressions) runs in goja against a small DOM, a live page connects its WebSocket to the app, and every event, patch and form rule is the real runtime's.
Package viewtest drives view pages end to end in a test, without a browser: the page is fetched over HTTP from the app, the view runtime (/_view/runtime.js and the compiled expressions) runs in goja against a small DOM, a live page connects its WebSocket to the app, and every event, patch and form rule is the real runtime's.

Jump to

Keyboard shortcuts

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