CORS Config Guide
CORS Headers Reference
| Header | Example | Purpose |
|---|---|---|
| Access-Control-Allow-Origin | https://app.com or * | Allowed origins |
| Access-Control-Allow-Methods | GET, POST, PUT, DELETE | Allowed HTTP methods |
| Access-Control-Allow-Headers | Content-Type, Authorization | Allowed request headers |
| Access-Control-Allow-Credentials | true | Allow cookies/auth |
| Access-Control-Max-Age | 86400 | Cache preflight (seconds) |
| Access-Control-Expose-Headers | X-Request-Id | Headers accessible to JS |
Go/Gin CORS Middleware
func CORSMiddleware(allowedOrigins []string) gin.HandlerFunc {
return func(c *gin.Context) {
origin := c.Request.Header.Get("Origin")
// Check if origin is allowed
for _, allowed := range allowedOrigins {
if origin == allowed {
c.Header("Access-Control-Allow-Origin", origin)
c.Header("Vary", "Origin")
break
}
}
c.Header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
c.Header("Access-Control-Allow-Headers", "Content-Type,Authorization,X-Request-ID")
c.Header("Access-Control-Max-Age", "86400")
// Handle preflight
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}
Common CORS Errors & Fixes
Error: No Access-Control-Allow-Origin header
Fix: Add CORS middleware to your server. Ensure OPTIONS preflight is handled.
Error: Wildcard origin with credentials
Fix: When using credentials:true, you cannot use wildcard (*). Specify exact origin.
Error: Request header not allowed
Fix: Add the header to Access-Control-Allow-Headers in the preflight response.