Skip to main content

CORS

Regius includes a CORS (Cross-Origin Resource Sharing) middleware with flexible configuration.

Features

  • Opt-out by default: CORS is enabled automatically with sensible defaults
  • Configurable origins: Allow specific domains or use wildcards
  • Configurable methods and headers: Control which HTTP methods and headers are permitted
  • Preflight support: Automatic handling of OPTIONS requests
  • Credentials support: Allow cookies and authorization headers in cross-origin requests
  • Flexible application: Apply globally or to specific route groups

Usage

CORS is applied globally by default when CORS_ENABLED=true (or unset). No additional code is required.

To apply CORS only to API routes, disable global CORS in .env:

CORS_ENABLED=false

Then manually apply it in your routes file:

r.Group(func(mux chi.Router) {
mux.Use(a.CORS(regius.CORSConfig{
Enabled: true,
AllowedOrigins: []string{"https://app.example.com"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"},
AllowCredentials: true,
}))
// API routes here
})

Configuration Options

config := regius.CORSConfig{
Enabled: true,
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type"},
ExposedHeaders: []string{},
MaxAge: 300,
AllowCredentials: true,
OptionsPassthrough: false,
Debug: false,
}
OptionTypeDescription
EnabledboolEnable/disable CORS
AllowedOrigins[]stringAllowed origins (use "*" for any)
AllowedMethods[]stringAllowed HTTP methods
AllowedHeaders[]stringAllowed request headers
ExposedHeaders[]stringHeaders exposed to the client
MaxAgeintPreflight cache duration in seconds
AllowCredentialsboolAllow cookies/auth headers
OptionsPassthroughboolLet OPTIONS requests pass through
DebugboolEnable debug logging

Environment Variables

CORS_ENABLED=true
CORS_ALLOWED_ORIGINS="*"
CORS_ALLOWED_METHODS="GET,POST,PUT,DELETE,OPTIONS,PATCH,HEAD"
CORS_ALLOWED_HEADERS="Accept,Authorization,Content-Type,X-CSRF-Token"
CORS_EXPOSED_HEADERS=""
CORS_ALLOW_CREDENTIALS=true
CORS_MAX_AGE=300