Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Go Gin CORS middleware is added but the browser still blocks the call

ErrorAccess to fetch at 'http://localhost:8080/api/items' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Short answer

Gin builds each route's handler chain when the route is registered, so a CORS middleware added after the routes does not cover them. Check the order first, then how OPTIONS is answered, then the gin-contrib/cors settings: exact origins, no wildcard with credentials, and every request header listed in AllowHeaders.

  • Applies to Gin v1 (gin-gonic/gin), gin-contrib/cors, current Go release
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Send the preflight yourself and read the status and headers. A plain body of 404 page not found or 405 method not allowed is Gin's default answer for a request that no handler took care of.

    curl -i -X OPTIONS http://localhost:8080/api/items \
      -H "Origin: http://localhost:5173" \
      -H "Access-Control-Request-Method: POST" \
      -H "Access-Control-Request-Headers: content-type,authorization"
  2. 2Match what you see, then jump to its fix

    1. 1Some routes return CORS headers and others do not: the ones declared before r.Use(cors...) are the ones withoutThe middleware is registered after the routesFix
    2. 2The preflight comes back as 404 page not found (or 405 method not allowed when HandleMethodNotAllowed is on), usually with the CORS headers set but the wrong statusYour own CORS middleware lets the OPTIONS request fall throughFix
    3. 3The OPTIONS request returns 401 or 403 with no Access-Control headers, while authenticated requests workAn auth middleware earlier in the chain rejects the preflightFix
    4. 4The client sends cookies or credentials: 'include', and the server answers with Access-Control-Allow-Origin: *Credentials are used with AllowAllOrigins or a wildcardFix
    5. 5The preflight has no Access-Control-Allow-Origin, and the origin in your list differs in scheme, host or port, or uses a * patternThe origin in AllowOrigins does not match the one the browser sendsFix
    6. 6Plain GET calls work, but calls with Authorization or a custom header fail at the preflightA request header is not listed in AllowHeadersFix

What does the error look like?

  • Access to fetch at 'http://localhost:8080/api/items' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
  • 404 page not found
  • 405 method not allowed

Cause 1 of 6

The middleware is registered after the routes

1Check

When you register a route, Gin copies the middleware that exists at that moment into the route's handler chain. A Use call placed later only affects routes registered after it. Read the order in your router setup.

grep -n "\.Use(\|\.GET(\|\.POST(\|\.PUT(\|\.DELETE(\|\.Group(" main.go

2Fix

Call Use with the CORS middleware first, right after creating the router, then declare the routes and groups.

r := gin.New()
r.Use(gin.Logger(), gin.Recovery())
r.Use(cors.New(cors.Config{
    AllowOrigins: []string{"http://localhost:5173"},
    AllowHeaders: []string{"Content-Type", "Authorization"},
}))

r.POST("/api/items", createItem) // registered after Use

3Verify

Request a route that used to lack the header and look for Access-Control-Allow-Origin.

curl -s -D - -o /dev/null -X POST http://localhost:8080/api/items -H "Origin: http://localhost:5173" -H "Content-Type: application/json" -d '{}' | grep -i access-control

Confirmed by raw.githubusercontent.com

Did this fix it?

Cause 2 of 6

Your own CORS middleware lets the OPTIONS request fall through

1Check

Middleware added with Use also runs for requests that match no route, and a preflight is an OPTIONS request that your routes usually do not declare. If your function sets headers and then calls c.Next(), Gin ends with 404 for the preflight, and the browser needs a success status.

grep -rn "Access-Control-Allow\|MethodOptions\|AbortWithStatus" --include=*.go .

2Fix

End the preflight inside the middleware with a success status, or switch to gin-contrib/cors, which answers OPTIONS with 204 by default.

func corsMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Header("Access-Control-Allow-Origin", "http://localhost:5173")
        c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization")
        c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
        if c.Request.Method == http.MethodOptions {
            c.AbortWithStatus(http.StatusNoContent)
            return
        }
        c.Next()
    }
}

3Verify

The preflight now returns 204 with the Access-Control headers.

curl -i -X OPTIONS http://localhost:8080/api/items -H "Origin: http://localhost:5173" -H "Access-Control-Request-Method: POST"

Confirmed by raw.githubusercontent.com

Did this fix it?

Cause 3 of 6

An auth middleware earlier in the chain rejects the preflight

1Check

Handlers run in the order they were added, and a browser never sends credentials on a preflight. If a JWT or session middleware comes before the CORS one and aborts, the CORS code never runs.

grep -n "\.Use(" main.go

2Fix

Register the CORS middleware before any authentication middleware.

r := gin.New()
r.Use(cors.New(corsConfig))   // first
r.Use(authMiddleware())       // after

api := r.Group("/api")
api.GET("/items", listItems)

3Verify

The preflight, sent without a token, returns 204.

curl -i -X OPTIONS http://localhost:8080/api/items -H "Origin: http://localhost:5173" -H "Access-Control-Request-Method: GET"

Confirmed by raw.githubusercontent.com

Did this fix it?

Cause 4 of 6

Credentials are used with AllowAllOrigins or a wildcard

1Check

In gin-contrib/cors, AllowAllOrigins does not work with credentialed requests, and AllowCredentials is meant for precise origins only. cors.Default() allows all origins.

grep -rn "cors.Default\|AllowAllOrigins\|AllowCredentials" --include=*.go .

2Fix

List the exact origins and set AllowCredentials. Set only one way of choosing origins.

r.Use(cors.New(cors.Config{
    AllowOrigins:     []string{"https://app.example.com"},
    AllowCredentials: true,
    AllowHeaders:     []string{"Content-Type", "Authorization"},
}))

3Verify

The response carries your single origin and Access-Control-Allow-Credentials: true.

curl -s -D - -o /dev/null -X OPTIONS http://localhost:8080/api/items -H "Origin: https://app.example.com" -H "Access-Control-Request-Method: GET" | grep -i access-control

Confirmed by github.com

Did this fix it?

Cause 5 of 6

The origin in AllowOrigins does not match the one the browser sends

1Check

AllowOrigins entries are matched exactly. A pattern like https://*.example.com only works when AllowWildcard is on, with a single * per entry; without it the library panics at start-up. Print what your config allows.

grep -rn "AllowOrigins\|AllowWildcard\|AllowOriginFunc" --include=*.go .

2Fix

Copy the origin from the browser's Origin header exactly, or enable wildcards for subdomains.

r.Use(cors.New(cors.Config{
    AllowOrigins:  []string{"http://localhost:5173", "https://*.example.com"},
    AllowWildcard: true,
}))

3Verify

Send the preflight with each origin you expect and check that it is echoed back.

curl -s -D - -o /dev/null -X OPTIONS http://localhost:8080/api/items -H "Origin: https://shop.example.com" -H "Access-Control-Request-Method: GET" | grep -i allow-origin

Confirmed by github.com

Did this fix it?

Cause 6 of 6

A request header is not listed in AllowHeaders

1Check

AllowHeaders is empty by default in the library; it is the list of non-simple request headers a browser may send. The header names the browser lists in Access-Control-Request-Headers must appear in the answer.

curl -s -D - -o /dev/null -X OPTIONS http://localhost:8080/api/items -H "Origin: http://localhost:5173" -H "Access-Control-Request-Method: POST" -H "Access-Control-Request-Headers: authorization,x-request-id" | grep -i access-control

2Fix

Add every header the front end sends.

r.Use(cors.New(cors.Config{
    AllowOrigins: []string{"http://localhost:5173"},
    AllowHeaders: []string{"Content-Type", "Authorization", "X-Request-Id"},
}))

3Verify

The preflight answer lists all three names in Access-Control-Allow-Headers.

curl -s -D - -o /dev/null -X OPTIONS http://localhost:8080/api/items -H "Origin: http://localhost:5173" -H "Access-Control-Request-Method: POST" -H "Access-Control-Request-Headers: authorization,x-request-id" | grep -i allow-headers

Confirmed by github.com

Did this fix it?

How do I stop it coming back?

  • Add the CORS middleware first, before authentication middleware and before every route or group.
  • Prefer gin-contrib/cors over a hand-written function, so OPTIONS handling and header rules are not copied by hand.
  • Keep allowed origins in configuration per environment, and never combine AllowAllOrigins with credentials.
  • Keep the preflight curl command in a Makefile target and run it before each release.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Web apps

The browser blocks your API response: no Access-Control-Allow-Origin header

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.example.com/orders. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

The browser received the response but refused to hand it to your script, because it did not carry an Access-Control-Allow-Origin header naming the page's origin.

4 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.