Fix CORSError: Access to XMLHttpRequest at 'http://localhost:8080/api/data' from origin 'http://localhost:3000' has been blocked by CORS policy in Gin
This error occurs when your Gin backend does not include the proper Access-Control-Allow-Origin headers, causing the browser to block cross-origin requests from your frontend. Fix it by adding the gin-contrib/cors middleware with the correct allowed origins, methods, and headers for your frontend domain.
Reading the Stack Trace
Here's what each line means:
- github.com/gin-contrib/cors.New.func1(0x14000226000) /go/pkg/mod/github.com/gin-contrib/cors@v1.5.0/cors.go:52 +0x1c8: The CORS middleware rejects the preflight OPTIONS request because the requesting origin is not in the allowed origins list.
- [GIN] 2024/03/15 - 16:00:05 | 403 | 0.204ms | 127.0.0.1 | OPTIONS /api/data: The preflight OPTIONS request returns 403, which tells the browser to block the subsequent actual request.
- github.com/gin-gonic/gin.(*Engine).handleHTTPRequest(0x14000128680, 0x14000226000): Gin routes the OPTIONS request through the middleware chain where CORS policy is enforced.
Common Causes
1. No CORS middleware configured
The Gin server has no CORS middleware, so no Access-Control-Allow-Origin header is set on responses.
func main() {
r := gin.Default()
// No CORS middleware
r.GET("/api/data", GetData)
r.Run(":8080")
}
2. AllowOrigins does not include frontend URL
The CORS config specifies allowed origins but omits the frontend development URL.
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"https://production.example.com"},
// Missing http://localhost:3000 for development
}))
3. Missing allowed headers for auth
The CORS config does not include Authorization in AllowHeaders, causing preflight to fail for authenticated requests.
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"http://localhost:3000"},
AllowMethods: []string{"GET", "POST"},
// Missing AllowHeaders: ["Authorization"]
}))
The Fix
Add the gin-contrib/cors middleware with explicit allowed origins that include your frontend URL. Specify all HTTP methods, headers (including Authorization), and enable credentials if using cookies or auth tokens.
func main() {
r := gin.Default()
r.GET("/api/data", GetData)
r.Run(":8080")
}
func main() {
r := gin.Default()
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"http://localhost:3000", "https://yourdomain.com"},
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Authorization"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
}))
r.GET("/api/data", GetData)
r.Run(":8080")
}
Testing the Fix
package main_test
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestCORS_PreflightRequest(t *testing.T) {
r := setupRouter()
req := httptest.NewRequest(http.MethodOptions, "/api/data", nil)
req.Header.Set("Origin", "http://localhost:3000")
req.Header.Set("Access-Control-Request-Method", "GET")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusNoContent, w.Code)
assert.Equal(t, "http://localhost:3000", w.Header().Get("Access-Control-Allow-Origin"))
}
func TestCORS_BlockedOrigin(t *testing.T) {
r := setupRouter()
req := httptest.NewRequest(http.MethodOptions, "/api/data", nil)
req.Header.Set("Origin", "http://evil.com")
req.Header.Set("Access-Control-Request-Method", "GET")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Empty(t, w.Header().Get("Access-Control-Allow-Origin"))
}
Run your tests:
go test ./... -v
Pushing Through CI/CD
git checkout -b fix/gin-cors-error,git add main.go,git commit -m "fix: add CORS middleware with allowed origins for frontend",git push origin fix/gin-cors-error
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.22'
- run: go mod download
- run: go vet ./...
- run: go test ./... -race -coverprofile=coverage.out
- run: go build ./...
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
go get github.com/bugstack/sdk
Step 2: Initialize
import "github.com/bugstack/sdk"
func init() {
bugstack.Init(os.Getenv("BUGSTACK_API_KEY"))
}
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run go test ./... locally to confirm CORS is configured correctly.
- Open a pull request with the CORS middleware addition.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify cross-origin requests work in staging.
Frequently Asked Questions
BugStack validates the CORS configuration against your frontend origins, runs preflight tests, and ensures no endpoints are inadvertently exposed before marking it safe to deploy.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
No. AllowAllOrigins: true disables CORS protection entirely. Always specify exact origins in production to prevent unauthorized cross-origin access.
The browser sends an OPTIONS preflight request first to check CORS policy, then the actual request. This is normal for cross-origin requests with custom headers.