How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Echo · Go

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

2024/03/15 16:30:05 echo: OPTIONS /api/data -> echo/middleware.CORSWithConfig.func1 | 403 | 0.104ms | 127.0.0.1 goroutine 34 [running]: runtime/debug.Stack() /usr/local/go/src/runtime/debug/stack.go:24 +0x5e github.com/labstack/echo/v4/middleware.CORSWithConfig.func1.1({0x1029e4f80, 0x14000226000}) /go/pkg/mod/github.com/labstack/echo/v4@v4.11.4/middleware/cors.go:103 +0x3e8 github.com/labstack/echo/v4.(*Echo).ServeHTTP(0x14000128680, {0x1029e4f80, 0x140001c40e0}, 0x140002b4000) /go/pkg/mod/github.com/labstack/echo/v4@v4.11.4/echo.go:669 +0x1a0

Here's what each line means:

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.

Before (broken)
func main() {
	e := echo.New()
	e.GET("/api/data", GetData)
	e.Start(":8080")
}
After (fixed)
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:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. 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:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. 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)

  1. Run go test ./... locally to confirm CORS preflight works.
  2. Open a pull request with the CORS middleware addition.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. 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.