extension

package
v1.23.1 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package extension is the plugin seam for nexus. A Plugin bundles the pieces a feature contributes to a nexus app — DI/options, dashboard routes, client SDK hooks, lifecycle callbacks — into a single value that callers pass to nexus.Run via Use.

The built-in auth and oauth2 modules are themselves Plugins; third parties build the same shape:

func Module(cfg Config) nexus.Option {
    return extension.Use(extension.Plugin{
        Name:    "feature-flags",
        Version: "0.1.0",
        Options: []nexus.Option{
            nexus.Provide(newStore(cfg)),
            nexus.AsQuery(NewListFlags),
        },
        Dashboard: &extension.Dashboard{
            Tab: &extension.Tab{ID: "flags", Label: "Flags"},
            Routes: []extension.Route{
                {Method: "GET", Path: "", Handler: listHandler},
            },
        },
        Lifecycle: &extension.Lifecycle{
            OnReady: warmCache,
        },
    })
}

The four contribution slots are independent — a plugin uses only the slots it needs. Options alone is equivalent to nexus.Module without the naming machinery; Dashboard, Client, and Lifecycle layer on the pieces nexus.Module doesn't currently expose.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Use

func Use(p Plugin) nexus.Option

Use converts a Plugin into a nexus.Option suitable for nexus.Run. It validates the plugin, then expands the contribution slots into the standard nexus.Option vocabulary.

Ordering is deterministic: validation → Options → plugin registration → Lifecycle → Dashboard routes → Client.Apply. Within Options the user controls order; the slots run after Options so any engine.Use() the plugin performs in Options is in effect before Dashboard routes mount.

Types

type Client

type Client struct {
	// Namespace is the SDK accessor (`nx.<namespace>.*`). Optional;
	// purely informational for now (surfaced via PluginRecord).
	Namespace string

	// Apply runs once during di.Start with the constructed *nexus.App
	// in scope. Use it to call app.SetClientAuthInfo, register
	// methods on app.ClientHandler(), etc. Return an error to abort
	// boot.
	Apply func(app *nexus.App) error
}

Client contribution: declares an SDK namespace + a one-shot Apply hook that runs at boot. Apply is the escape hatch for plugins that need to mutate the client manifest (e.g. auth's ExtractorInfo) — future versions of this struct will add typed contribution helpers.

type ClientContributor added in v0.54.0

type ClientContributor interface {
	NexusContribute(ctx GenerateContext) ([]File, error)
}

ClientContributor is the optional interface a plugin can implement (and surface via Plugin.Contributor) to add extra files to whatever generator the active Generate driver runs. The frontend extension is the canonical consumer: at Render time it asks the App for every registered contributor and merges the returned files into its output tree.

NexusContribute receives the same GenerateContext the driver sees, including the framework choice in Extras["frontend.framework"] — contributors that ship per-framework adapters (a Vue auth composable vs. a React hook, say) branch on that key.

func StaticContributor added in v0.54.0

func StaticContributor(files []File) ClientContributor

StaticContributor wraps an already-rendered file list as a ClientContributor. The frontend codegen CLI uses this to slot HTTP-fetched contributions back into ctx.Contributors — the renderer's contributor loop doesn't care whether the bytes were produced in-process or fetched from a remote app.

The returned contributor ignores the GenerateContext entirely; the bytes are baked in at construction time.

type ContributorFunc added in v0.54.0

type ContributorFunc func(ctx GenerateContext) ([]File, error)

ContributorFunc is an adapter so plugins can register a function without declaring a named type. Mirrors http.HandlerFunc — the receiver method calls the underlying function.

func (ContributorFunc) NexusContribute added in v0.54.0

func (f ContributorFunc) NexusContribute(ctx GenerateContext) ([]File, error)

NexusContribute satisfies ClientContributor for ContributorFunc.

type Dashboard

type Dashboard struct {
	// Tab is an entry in the dashboard nav. nil → no tab (the plugin
	// only adds backend routes, no UI surface).
	Tab *Tab

	// Routes are mounted under /__nexus/<plugin-name>/<route.Path>.
	// Path may be empty (mounts at /__nexus/<plugin-name>) or start
	// with "/".
	Routes []Route

	// LiveEvents lists trace.Bus event names this plugin emits that
	// the dashboard should forward to its WebSocket clients. Empty
	// is fine — only set this if your plugin publishes custom events.
	LiveEvents []string
}

Dashboard contribution: an optional nav Tab and a set of HTTP Routes mounted under /__nexus/<plugin-name>/...

type File added in v0.54.0

type File struct {
	Path string
	Body []byte
}

File is one generated artifact a driver (or a contributor) emits. Path is forward-slash relative to the driver's OutDir; Body is the raw bytes. Mirrors nexus.GeneratedFile so we can route values across the package boundary without an import cycle, but the user-facing type lives here so plugin authors never touch the nexus internals.

type Generate added in v0.54.0

type Generate struct {
	OutDir func(app *nexus.App) (string, error)
	Render func(ctx GenerateContext) ([]File, error)
}

Generate declares a codegen driver. OutDir resolves the absolute directory the driver wants files written to; Render produces the file tree. Both are required. The shape mirrors nexus.GenerateDriver — Use() converts between them — so plugin authors never import the nexus internals to write a driver.

type GenerateContext added in v0.54.0

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

GenerateContext is the input handed to a driver's Render callback. Mirrors nexus.GenerateContext so plugin authors import only the extension package.

type Lifecycle

type Lifecycle struct {
	// OnBoot fires during di.Start, before the HTTP listener binds.
	// Returning a non-nil error aborts boot.
	OnBoot func(ctx context.Context, app *nexus.App) error

	// OnReady fires after OnBoot and after the listener is bound.
	// Use for warming caches or kicking off background work that
	// depends on the app being ready to serve.
	OnReady func(ctx context.Context, app *nexus.App) error

	// OnShutdown fires during di.Stop. The context carries the
	// shutdown deadline.
	OnShutdown func(ctx context.Context) error
}

Lifecycle hooks tied to the fx app lifecycle. OnBoot and OnReady both fire during di.Start (OnBoot before any route serves, OnReady after) — OnShutdown fires during di.Stop. All three are optional.

type Plugin

type Plugin struct {
	// Name uniquely identifies the plugin. Used as the dashboard
	// route prefix (/__nexus/<name>/...) and the discovery key.
	// Must be kebab-case and unique within an app.
	Name string

	// Version is a free-form version string surfaced on the
	// dashboard. Semver recommended but not enforced.
	Version string

	// Icon is a lucide-style icon name shown next to the plugin in the
	// dashboard. Optional — when empty the dashboard falls back to the
	// plugin's Tab icon (if any) and then to a default extension icon.
	Icon string

	// Options is the standard nexus option slice — same values you'd
	// pass to nexus.Module: Provide, Invoke, AsRest, AsQuery, Use, etc.
	// They run in order before the contribution-slot invokes below,
	// so plugin-owned engine.Use() calls land before plugin Dashboard
	// routes mount.
	Options []nexus.Option

	// Lifecycle attaches OnBoot/OnReady/OnShutdown callbacks via the
	// fx lifecycle. Optional.
	Lifecycle *Lifecycle

	// Dashboard contributes a nav tab + HTTP routes under
	// /__nexus/<name>/... so a plugin can ship its own admin
	// surface without touching the dashboard package. Optional.
	Dashboard *Dashboard

	// Client lets a plugin extend the generated SDK — declaring a
	// namespace and an Apply hook that runs once the App is built.
	// Optional.
	Client *Client

	// Generate marks the plugin as a codegen driver. Exactly one
	// plugin per app may set this; the second registration panics at
	// boot. The frontend extension sets it; most plugins don't. See
	// the Generate struct doc for the contract.
	Generate *Generate

	// Contributor adds plugin-specific files to whatever the active
	// Generate driver renders. Unlike Generate, Contributor is many-
	// per-app: auth might publish auth/index.ts, oauth2 might publish
	// oauth2/index.ts, and both ride alongside the frontend driver's
	// own _client.ts / index.ts. The driver merges Contributor output
	// into its file tree at Render time. Optional — only set this on
	// plugins that have framework-flavored code to ship.
	Contributor ClientContributor
}

Plugin describes a feature contribution to a nexus app. Name is the only required field; the contribution slots are all optional, so a minimal plugin (Options only) is valid.

type Route

type Route struct {
	Method  string // "GET", "POST", etc.
	Path    string // "" or "/subpath"
	Handler httpx.HandlerFunc
}

Route is an HTTP endpoint mounted under the plugin's dashboard prefix.

type Tab

type Tab struct {
	ID    string // url-safe identifier; uniqueness is the plugin's responsibility
	Label string // human-readable label
	Icon  string // optional lucide-style icon name; UI falls back to a default
}

Tab is a dashboard navigation entry. The dashboard UI renders it as a clickable label; the ID is used as the persisted ?tab= value.

Directories

Path Synopsis
Package auth is nexus's built-in authentication surface.
Package auth is nexus's built-in authentication surface.
Package cache provides a cache for nexus apps.
Package cache provides a cache for nexus apps.
redis
Package redis is the opt-in Redis backend for the nexus cache.
Package redis is the opt-in Redis backend for the nexus cache.
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.
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.
Package cors implements CORS (Cross-Origin Resource Sharing) for nexus apps.
Package cors implements CORS (Cross-Origin Resource Sharing) for nexus apps.
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.
Package dashboard mounts the nexus introspection surface under /__nexus.
Package dashboard mounts the nexus introspection surface under /__nexus.
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).
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.
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.
iauth
Package iauth bridges nexus's auth extension to Inertia: an auth.ErrorHandler that renders auth denials the way each caller expects — a redirect for page navigations (Inertia visits and full-page loads), the error in the array for GraphQL, and JSON for API/SDK clients.
Package iauth bridges nexus's auth extension to Inertia: an auth.ErrorHandler that renders auth denials the way each caller expects — a redirect for page navigations (Inertia visits and full-page loads), the error in the array for GraphQL, and JSON for API/SDK clients.
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.
Package oauth2 wires a go-oauth2/oauth2/v4 server into a nexus app and bridges its access-token store to nexus.auth so handlers can gate themselves with auth.Required() / auth.Requires().
Package oauth2 wires a go-oauth2/oauth2/v4 server into a nexus app and bridges its access-token store to nexus.auth so handlers can gate themselves with auth.Required() / auth.Requires().
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.
Package peer wires typed RPC between nexus apps.
Package peer wires typed RPC between nexus apps.
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.
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.
Package tour ships a Spring-Boot-style guided-tour plugin for nexus apps.
Package tour ships a Spring-Boot-style guided-tour plugin for nexus apps.
Package visitors counts page views on a nexus app and exposes the totals over a small public API the frontend polls.
Package visitors counts page views on a nexus app and exposes the totals over a small public API the frontend polls.

Jump to

Keyboard shortcuts

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