cors

package
v0.83.4 Latest Latest
Warning

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

Go to latest
Published: May 23, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package cors implements CORS (Cross-Origin Resource Sharing) for nexus apps. Two API surfaces ride the same engine:

  1. cors.Plugin(Config) — installs the policy globally as application middleware. Most apps want exactly one CORS policy and this is the right choice for them.

  2. cors.NewMiddleware(Config) — returns a per-route middleware bundle suitable for nexus.Use. Use when different endpoints need different policies (e.g. a public "*"-allowed endpoint mixed with credentialed endpoints that lock to one origin).

Both paths share the same Config / matcher / response-writing code; the only difference is where in the request graph the middleware attaches.

Manifest integration: a `cors:` block in nexus.toml is read by Plugin() at boot and overrides the in-code Config field-by-field (manifest wins where set). environment_overrides can flip policies per environment — typical pattern is permissive in preview, strict in production.

# nexus.toml
cors:
  allow_origins: [https://app.example.com]
  allow_credentials: true
  allow_methods: [GET, POST, PUT, DELETE]
  allow_headers: [Content-Type, Authorization]
  max_age: 3600

environment_overrides:
  preview:
    cors:
      allow_origins: ["*"]
      allow_credentials: false   # wildcard forbids credentials

Reference: https://fetch.spec.whatwg.org/#http-cors-protocol

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewMiddleware

func NewMiddleware(cfg Config) middleware.Middleware

NewMiddleware returns a per-route middleware bundle. Use when a subset of routes needs a different policy from the global one (typically: a public "*"-allowed endpoint mixed in with otherwise credentialed routes).

var publicAPI = nexus.Use(cors.NewMiddleware(cors.Config{
    AllowOrigins: []string{"*"},
}))

nexus.AsRest("GET", "/api/public", handler, publicAPI),

func Plugin

func Plugin(cfg Config) nexus.Option

Plugin attaches CORS as a global application middleware. The effective policy is the merge of the in-code Config and the `cors:` block in nexus.toml — manifest wins where set. Validation runs at OnBoot, so a misconfigured policy aborts boot with a readable error before any listener binds.

cors.Plugin(cors.Config{
    AllowOrigins:     []string{"https://app.example.com"},
    AllowCredentials: true,
})

Types

type Config

type Config struct {
	// AllowOrigins is the list of origins permitted to read responses.
	// Each entry is one of:
	//
	//	"*"                          wildcard — any origin (not combinable with credentials)
	//	"https://app.example.com"    exact match (scheme + host + optional port)
	//	"https://*.example.com"      subdomain wildcard (one level)
	//
	// Empty list is a misconfiguration — the plugin refuses to start
	// rather than silently allow nothing (which would block every
	// cross-origin request — usually the operator's mistake, not
	// intent).
	AllowOrigins []string

	// AllowOriginFunc is an escape hatch when the static list can't
	// express the policy (e.g. "any origin matching a Postgres
	// allowlist"). Takes the request's Origin header and returns
	// (allow, matchedOrigin). The matchedOrigin is what the response
	// header echoes back — leaving it as the request's Origin is
	// fine; rewriting lets advanced cases force a canonical form.
	//
	// When set, AllowOrigins is ignored. Manifest-driven config
	// cannot populate this (it's Go-only); operators who need it
	// pass it in-code.
	AllowOriginFunc func(origin string) (allow bool, matched string)

	// AllowMethods is the list of HTTP methods served. Default:
	// [GET, HEAD, POST, PUT, PATCH, DELETE]. The spec considers
	// GET/HEAD/POST "simple" and exempt from preflight, but we
	// still advertise them in the preflight response for clients
	// that fire one anyway.
	AllowMethods []string

	// AllowHeaders is the list of request headers permitted on
	// preflighted requests. Default: [Accept, Content-Type,
	// Authorization, X-Requested-With]. Browsers send the request's
	// headers in Access-Control-Request-Headers; we echo back the
	// intersection of that and AllowHeaders. Set to ["*"] for
	// "echo whatever the browser asks for" — convenient in dev,
	// risky in production.
	AllowHeaders []string

	// ExposeHeaders is the list of response headers the browser is
	// allowed to surface to JavaScript. Without this, only the
	// "CORS-safelisted" set is readable (Cache-Control,
	// Content-Language, Content-Length, Content-Type, Expires,
	// Last-Modified, Pragma). Set for any custom header your app
	// emits that callers must read — typically pagination
	// (X-Total-Count), rate-limit (X-RateLimit-*), or auth
	// (X-Refresh-Token).
	ExposeHeaders []string

	// AllowCredentials enables Access-Control-Allow-Credentials:
	// true. Required for cross-origin cookies + Authorization
	// headers. INCOMPATIBLE with AllowOrigins=["*"]; validation
	// rejects that combination at boot.
	AllowCredentials bool

	// MaxAge is the number of seconds browsers may cache the
	// preflight response. Default: 600 (10 minutes). Set to 86400
	// (24h) in production to reduce preflight traffic; lower in
	// dev so policy changes take effect immediately.
	MaxAge int

	// Disabled, when true, makes the middleware a no-op. Useful in
	// environments where an upstream proxy or CDN already handles
	// CORS — the plugin still loads, but its handlers pass through.
	Disabled bool
}

Config controls every aspect of the policy. Zero values produce sensible defaults; only AllowOrigins is required for a useful policy.

Jump to

Keyboard shortcuts

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