Almost every frontend engineer has hit the infamous red console error while integrating an API: Access to fetch at 'https://api.example.com/v1/orders' from origin 'https://app.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Even more confusingly, the exact same endpoint works in curl and Postman!
That happens because CORS (Cross-Origin Resource Sharing) is enforced strictly by the web browser’s Same-Origin Policy, never by `curl` or server-to-server HTTP clients. Fixing it properly requires understanding preflight `OPTIONS` requests, credential rules, and CDN `Vary: Origin` caching across **CodeIgniter 4**, **ASP.NET Core**, and **Nginx**.
Simple Request vs. Preflighted OPTIONS Request
| Browser Request Characteristics | Preflight `OPTIONS` Sent? | Required Backend Behavior |
|---|---|---|
GET / HEAD / POST with only safelisted headers & form/text content-type |
No (direct request) | Response includes `Access-Control-Allow-Origin` + `Vary: Origin` |
PUT, PATCH, DELETE, Content-Type: application/json, or Authorization: Bearer header |
Yes (browser sends `OPTIONS` first!) | Backend must answer `OPTIONS` with `204`/`200` before auth filters run + `Allow-Methods` / `Allow-Headers` |
1. Fixing CORS Properly in CodeIgniter 4.5+ (Built-In Cors Filter)
CodeIgniter 4.5+ includes a first-party \CodeIgniter\Filters\Cors filter—so you do not need fragile third-party packages or manual `header()` calls inside controllers. Enable it on API routes in `app/Config/Filters.php` and configure an explicit origin allowlist in `app/Config/Cors.php`:
<?php
// app/Config/Cors.php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Cors extends BaseConfig
{
public array $default = [
'allowedOrigins' => ['https://app.technolila.com', 'http://localhost:3000'],
'allowedOriginsPatterns' => [],
'supportsCredentials' => true,
'allowedHeaders' => ['Authorization', 'Content-Type', 'X-Requested-With'],
'exposedHeaders' => ['X-Request-Id'],
'allowedMethods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
'maxAge' => 7200,
];
}
Crucial CodeIgniter Filter Ordering Rule: Register `'cors'` **before** `'jwtAuth'` or `'csrf'` inside `$globals['before']` (or route filters). A browser preflight `OPTIONS` request **never carries your `Authorization: Bearer` header or cookies**! If your authentication filter runs before CORS, the preflight fails with `401 Unauthorized` and the browser blocks the real `POST`/`PUT` request.
2. Fixing CORS in ASP.NET Core (Minimal APIs & Controllers)
In ASP.NET Core `Program.cs`, middleware registration order is equally strict: `app.UseCors("ApiPolicy")` must appear **after `UseRouting()` and before `UseAuthentication()` / `UseAuthorization()`**:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy("ApiPolicy", policy =>
{
policy.WithOrigins("https://app.technolila.com", "http://localhost:3000")
.WithMethods("GET", "POST", "PUT", "PATCH", "DELETE")
.WithHeaders("Authorization", "Content-Type", "X-Requested-With")
.AllowCredentials()
.SetPreflightMaxAge(TimeSpan.FromHours(2));
});
});
var app = builder.Build();
app.UseRouting();
app.UseCors("ApiPolicy");
app.UseAuthentication();
app.UseAuthorization();
3. The 3 Fatal CORS Mistakes That Break Production Apps
Mistake 1: Wildcard * Combined With Access-Control-Allow-Credentials: true
The Fetch specification explicitly forbids returning `Access-Control-Allow-Origin: *` whenever `Allow-Credentials: true` is present. If your frontend uses `fetch(url, { credentials: 'include' })` or `Authorization` cookies, you must validate the incoming `Origin` header against an explicit allowlist and echo back that single trusted origin.
Mistake 2: Duplicate Headers From Both Nginx AND Your PHP/.NET App
If Nginx adds `Access-Control-Allow-Origin: https://app.example.com` *and* CodeIgniter 4 also adds it, the browser receives `https://app.example.com, https://app.example.com` and immediately rejects the response because multiple values are invalid! Configure CORS in **one layer only** (preferably the application layer if allowlists are dynamic, or Nginx if static).
Mistake 3: Forgetting Vary: Origin Behind Cloudflare or CDNs
When your API echoes back `https://staging.example.com` dynamically, a CDN without `Vary: Origin` will cache that response and serve it to visitors on `https://app.example.com`, breaking CORS randomly across regions.
Security Note: CORS Is Not Authentication
Never assume CORS protects private endpoints against malicious scripts—server-side tools and mobile clients ignore CORS completely, and browser `POST` forms can still execute cross-site state changes unless you enforce Bearer tokens or CSRF checks (JWT Security Guide and CSP Header Generator).
Frequently Asked Questions
Why did my API work on `GET` in Chrome, then fail with CORS on `POST` JSON?
A plain `GET` without custom headers skips preflight, whereas `POST` with `Content-Type: application/json` triggers an automatic `OPTIONS` preflight request. If your route only registered `$routes->post(...)` without handling `OPTIONS`, the router returned `404` or `405` on the preflight.