CORS Config Guide

CORS Headers Reference

HeaderExamplePurpose
Access-Control-Allow-Originhttps://app.com or *Allowed origins
Access-Control-Allow-MethodsGET, POST, PUT, DELETEAllowed HTTP methods
Access-Control-Allow-HeadersContent-Type, AuthorizationAllowed request headers
Access-Control-Allow-CredentialstrueAllow cookies/auth
Access-Control-Max-Age86400Cache preflight (seconds)
Access-Control-Expose-HeadersX-Request-IdHeaders 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.