Skip to content

Commit f6223da

Browse files
Add docs from gofiber/fiber@73e9196
1 parent cb23ed3 commit f6223da

File tree

1 file changed

+171
-0
lines changed

1 file changed

+171
-0
lines changed

docs/core/middleware/cors.md

Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,12 @@ The CORS middleware works by adding the necessary CORS headers to responses from
169169

170170
When a request comes in, the middleware first checks if it's a preflight request, which is a CORS mechanism to determine whether the actual request is safe to send. Preflight requests are HTTP OPTIONS requests with specific CORS headers. If it's a preflight request, the middleware responds with the appropriate CORS headers and ends the request.
171171

172+
:::note
173+
Preflight requests are typically sent by browsers before making actual cross-origin requests, especially for methods other than GET or POST, or when custom headers are used.
174+
175+
A preflight request is an HTTP OPTIONS request that includes the `Origin`, `Access-Control-Request-Method`, and optionally `Access-Control-Request-Headers` headers. The browser sends this request to check if the server allows the actual request method and headers.
176+
:::
177+
172178
If it's not a preflight request, the middleware adds the CORS headers to the response and passes the request to the next handler. The actual CORS headers added depend on the configuration of the middleware.
173179

174180
The `AllowOrigins` option controls which origins can make cross-origin requests. The middleware handles different `AllowOrigins` configurations as follows:
@@ -197,6 +203,171 @@ The `MaxAge` option indicates how long the results of a preflight request can be
197203

198204
The `Vary` header is used in this middleware to inform the client that the server's response to a request. For or both preflight and actual requests, the Vary header is set to `Access-Control-Request-Method` and `Access-Control-Request-Headers`. For preflight requests, the Vary header is also set to `Origin`. The `Vary` header is important for caching. It helps caches (like a web browser's cache or a CDN) determine when a cached response can be used in response to a future request, and when the server needs to be queried for a new response.
199205

206+
## Infrastructure Considerations
207+
208+
When deploying Fiber applications behind infrastructure components like CDNs, API gateways, load balancers, or reverse proxies, you have two main options for handling CORS:
209+
210+
### Option 1: Use Infrastructure-Level CORS (Recommended)
211+
212+
**For most production deployments, it's often preferable to handle CORS at the infrastructure level** rather than in your Fiber application. This approach offers several advantages:
213+
214+
- **Better Performance**: CORS headers are added at the edge, closer to the client
215+
- **Reduced Server Load**: Preflight requests are handled without reaching your application
216+
- **Centralized Configuration**: Manage CORS policies alongside other infrastructure settings
217+
- **Built-in Caching**: Infrastructure providers optimize CORS response caching
218+
219+
**Common infrastructure CORS solutions:**
220+
221+
- **CDNs**: CloudFront, CloudFlare, Azure CDN - handle CORS at edge locations
222+
- **API Gateways**: AWS API Gateway, Google Cloud API Gateway - centralized CORS management
223+
- **Load Balancers**: Application Load Balancers with CORS rules
224+
- **Reverse Proxies**: Nginx, Apache with CORS modules
225+
226+
If using infrastructure-level CORS, **disable Fiber's CORS middleware** to avoid conflicts:
227+
228+
```go
229+
// Don't use both - choose one approach
230+
// app.Use(cors.New()) // Remove this line when using infrastructure CORS
231+
```
232+
233+
### Option 2: Application-Level CORS (Fiber Middleware)
234+
235+
Use Fiber's CORS middleware when you need:
236+
237+
- **Dynamic origin validation** based on application logic
238+
- **Fine-grained control** over CORS policies per route
239+
- **Integration with application state** (database-driven origins, etc.)
240+
- **Development environments** where infrastructure CORS isn't available
241+
242+
If choosing this approach, ensure that **all CORS headers reach your Fiber application unchanged**.
243+
244+
### Required Headers for CORS Preflight Requests
245+
246+
For CORS preflight requests to work correctly, these headers **must not be stripped or modified by caching layers**:
247+
248+
- `Origin` - Required to identify the requesting origin
249+
- `Access-Control-Request-Method` - Required to identify the HTTP method for the actual request
250+
- `Access-Control-Request-Headers` - Optional, contains custom headers the actual request will use
251+
- `Access-Control-Request-Private-Network` - Optional, for private network access requests
252+
253+
:::warning Critical Preflight Requirement
254+
If the `Access-Control-Request-Method` header is missing from an OPTIONS request, Fiber will not recognize them as CORS preflight requests. Instead, they'll be treated as regular OPTIONS requests, which typically return `405 Method Not Allowed` since most applications don't define explicit OPTIONS handlers.
255+
:::
256+
257+
### CORS Response Headers (Set by Fiber)
258+
259+
The middleware sets these response headers based on your configuration:
260+
261+
**For all CORS requests:**
262+
263+
- `Access-Control-Allow-Origin` - Set to the allowed origin or "*"
264+
- `Access-Control-Allow-Credentials` - Set to "true" when `AllowCredentials: true`
265+
- `Access-Control-Expose-Headers` - Lists headers the client can access
266+
- `Vary` - Set to "Origin" (unless wildcard origins are used)
267+
268+
**For preflight responses only:**
269+
270+
- `Access-Control-Allow-Methods` - Lists allowed HTTP methods
271+
- `Access-Control-Allow-Headers` - Lists allowed request headers (or echoes the request)
272+
- `Access-Control-Max-Age` - Cache duration for preflight results (if MaxAge > 0)
273+
- `Access-Control-Allow-Private-Network` - Set to "true" when private network access is allowed
274+
- `Vary` - Set to "Access-Control-Request-Method, Access-Control-Request-Headers, Origin"
275+
276+
### Common Infrastructure Issues
277+
278+
**CDNs (CloudFront, CloudFlare, etc.)**:
279+
280+
- Configure cache policies to forward all CORS headers
281+
- Ensure OPTIONS requests are not cached inappropriately or cache them correctly with proper Vary headers
282+
- Don't strip or modify CORS request headers
283+
284+
**API Gateways**:
285+
286+
- Choose either gateway-level CORS OR application-level CORS, not both
287+
- If using gateway CORS, disable Fiber's CORS middleware
288+
- If forwarding to Fiber, ensure all headers pass through unchanged
289+
290+
**Load Balancers/Reverse Proxies**:
291+
292+
- Preserve all HTTP headers, especially CORS-related ones
293+
- Don't modify or strip `Origin`, `Access-Control-Request-*` headers
294+
295+
**WAFs/Security Services**:
296+
297+
- Whitelist CORS headers in security rules
298+
- Ensure OPTIONS requests with CORS headers aren't blocked
299+
300+
### Debugging CORS Issues
301+
302+
Add this middleware **before** your CORS configuration to debug what headers Fiber receives:
303+
304+
```go
305+
// Debug middleware to log CORS preflight requests
306+
// Only use in development or testing environments
307+
app.Use(func(c *fiber.Ctx) error {
308+
if c.Method() == "OPTIONS" {
309+
fmt.Printf("OPTIONS %s\n", c.Path())
310+
fmt.Printf(" Origin: %s\n", c.Get("Origin"))
311+
fmt.Printf(" Access-Control-Request-Method: %s\n", c.Get("Access-Control-Request-Method"))
312+
fmt.Printf(" Access-Control-Request-Headers: %s\n", c.Get("Access-Control-Request-Headers"))
313+
}
314+
return c.Next()
315+
})
316+
317+
app.Use(cors.New(cors.Config{
318+
AllowOrigins: []string{"https://yourdomain.com"},
319+
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
320+
}))
321+
```
322+
323+
Test CORS preflight directly with curl:
324+
325+
```bash
326+
# Test preflight request
327+
curl -X OPTIONS https://your-app.com/api/test \
328+
-H "Origin: https://yourdomain.com" \
329+
-H "Access-Control-Request-Method: POST" \
330+
-H "Access-Control-Request-Headers: Content-Type" \
331+
-v
332+
333+
# Test simple CORS request
334+
curl -X GET https://your-app.com/api/test \
335+
-H "Origin: https://yourdomain.com" \
336+
-v
337+
```
338+
339+
### Caching Considerations
340+
341+
The middleware sets appropriate `Vary` headers to ensure proper caching:
342+
343+
- **Non-wildcard origins**: `Vary: Origin` is set to cache responses per origin
344+
- **Preflight requests**: `Vary: Access-Control-Request-Method, Access-Control-Request-Headers, Origin`
345+
- **OPTIONS without preflight headers**: `Vary: Origin` to avoid cache poisoning
346+
347+
Ensure your infrastructure respects these `Vary` headers for correct caching behavior.
348+
349+
### Choosing the Right Approach
350+
351+
| Scenario | Recommended Approach |
352+
|----------|---------------------|
353+
| Production with CDN/API Gateway | Infrastructure-level CORS |
354+
| Dynamic origin validation needed | Application-level CORS |
355+
| Microservices with different CORS policies | Application-level CORS |
356+
| Simple static origins | Infrastructure-level CORS |
357+
| Development/testing | Application-level CORS |
358+
| High traffic applications | Infrastructure-level CORS |
359+
360+
:::tip Infrastructure CORS Configuration
361+
Most cloud providers offer comprehensive CORS documentation:
362+
363+
- [AWS CloudFront CORS](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/header-caching.html#header-caching-web-cors)
364+
- [Google Cloud CORS](https://cloud.google.com/storage/docs/cross-origin)
365+
- [Azure CDN CORS](https://docs.microsoft.com/en-us/azure/cdn/cdn-cors)
366+
- [CloudFlare CORS](https://developers.cloudflare.com/fundamentals/get-started/reference/http-request-headers/#cf-connecting-ip)
367+
368+
Configure CORS at the infrastructure level when possible for optimal performance and reduced complexity.
369+
:::
370+
200371
## Security Considerations
201372

202373
When configuring CORS, misconfiguration can potentially expose your application to various security risks. Here are some secure configurations and common pitfalls to avoid:

0 commit comments

Comments
 (0)