LogoPly
Middleware

CORS

Cross-origin resource sharing for Ply routes.

CORS

middleware.CORS adds cross-origin headers and answers preflight requests. It uses a whitelist by default only when you pass AllowedOrigins.

app.Use(middleware.CORS(middleware.CORSOptions{
	AllowedOrigins:   []string{"https://app.example.com"},
	AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE"},
	AllowedHeaders:   []string{"Content-Type", "Authorization"},
	ExposedHeaders:   []string{"X-Request-ID"},
	AllowCredentials: true,
	MaxAge:           3600,
}))

Options

FieldDefaultDescription
AllowedOrigins["*"]Origins allowed to call the API
AllowedMethodsGET, POST, PUT, PATCH, DELETE, HEAD, OPTIONSMethods advertised during preflight
AllowedHeadersOrigin, Content-Type, Accept, AuthorizationRequest headers advertised during preflight
ExposedHeadersemptyResponse headers readable by browser code
AllowCredentialsfalseAdds Access-Control-Allow-Credentials: true
MaxAge86400Preflight cache time in seconds

Behavior

  • Requests without an Origin header continue normally.
  • A matching origin receives Access-Control-Allow-Origin.
  • With a wildcard origin and credentials disabled, the response uses *.
  • With credentials enabled, the response echoes the request origin and sets Vary: Origin.
  • An OPTIONS request with an origin ends with 204 No Content after the CORS headers are written. The route handler does not run.

Credentials

Do not combine AllowedOrigins: ["*"] with AllowCredentials: true unless you understand the risk. The middleware echoes the origin in that mode, but a wildcard policy still allows any site to send credentialed requests. Use an explicit origin list for cookie or authorization-based APIs.

Ordering

Place CORS before authentication so preflight requests are answered without a token:

app.Use(
	middleware.CORS(middleware.CORSOptions{
		AllowedOrigins: []string{"https://app.example.com"},
		AllowedHeaders: []string{"Content-Type", "Authorization"},
	}),
	middleware.AuthJWT(secret),
)