Fix CORSError: Access to fetch at 'http://localhost:8080/api/data' from origin 'http://localhost:5173' has been blocked by CORS policy in Echo
This error occurs when your Echo backend does not include CORS headers, causing the browser to block cross-origin requests from your frontend dev server. Fix it by adding Echo's built-in 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/labstack/echo/v4/middleware.CORSWithConfig.func1.1({0x1029e4f80, 0x14000226000}): Echo's CORS middleware rejects the preflight request because the Origin header value is not in the allowed origins list.
- echo: OPTIONS /api/data -> echo/middleware.CORSWithConfig.func1 | 403: The OPTIONS preflight request returns 403, telling the browser to block the actual cross-origin request.
- github.com/labstack/echo/v4.(*Echo).ServeHTTP(0x14000128680, {0x1029e4f80, 0x140001c40e0}, 0x140002b4000): Echo processes the incoming preflight request through its middleware chain.
Common Causes
1. No CORS middleware configured
The Echo server has no CORS middleware, so no Access-Control-Allow-Origin header is added to responses.
func main() {
e := echo.New()
// No CORS middleware
e.GET("/api/data", GetData)
e.Start(":8080")
}
2. AllowOrigins missing the dev server URL
The CORS config specifies production origins but omits the Vite/React dev server URL.
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"https://production.example.com"},
// Missing http://localhost:5173
}))
3. AllowHeaders missing Content-Type
POST/PUT requests with JSON bodies fail preflight because Content-Type is not in AllowHeaders.
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"http://localhost:5173"},
AllowMethods: []string{echo.GET, echo.POST},
// Missing AllowHeaders
}))
The Fix
Add Echo's built-in CORSWithConfig middleware with explicit allowed origins including your development frontend URL. Specify the HTTP methods and headers your API uses, including Authorization for authenticated requests.
func main() {
e := echo.New()
e.GET("/api/data", GetData)
e.Start(":8080")
}
func main() {
e := echo.New()
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"http://localhost:5173", "https://yourdomain.com"},
AllowMethods: []string{echo.GET, echo.POST, echo.PUT, echo.DELETE, echo.OPTIONS},
AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAuthorization},
AllowCredentials: true,
MaxAge: 3600,
}))
e.GET("/api/data", GetData)
e.Start(":8080")
}
Testing the Fix
package main_test
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/stretchr/testify/assert"
)
func TestCORS_AllowedOrigin(t *testing.T) {
e := setupEcho()
req := httptest.NewRequest(http.MethodOptions, "/api/data", nil)
req.Header.Set("Origin", "http://localhost:5173")
req.Header.Set("Access-Control-Request-Method", "GET")
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
assert.Equal(t, http.StatusNoContent, rec.Code)
assert.Equal(t, "http://localhost:5173", rec.Header().Get("Access-Control-Allow-Origin"))
}
func TestCORS_BlockedOrigin(t *testing.T) {
e := setupEcho()
req := httptest.NewRequest(http.MethodOptions, "/api/data", nil)
req.Header.Set("Origin", "http://evil.com")
req.Header.Set("Access-Control-Request-Method", "GET")
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
assert.Empty(t, rec.Header().Get("Access-Control-Allow-Origin"))
}
Run your tests:
go test ./... -v
Pushing Through CI/CD
git checkout -b fix/echo-cors-error,git add main.go,git commit -m "fix: add CORS middleware with allowed origins for frontend",git push origin fix/echo-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 preflight works.
- 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 in staging.
Frequently Asked Questions
BugStack validates CORS configuration against your frontend origins, tests preflight requests, 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.
In development, your frontend runs on a different port (e.g., :5173) than your backend (:8080). In production, they often share the same domain, so CORS does not apply.
No. Browsers reject this combination. When using credentials (cookies/auth headers), you must specify exact origins.