Solving CORS Issues: Wildcards vs Dynamic Origin Matching

Why Browsers Block CORS

Cross-Origin Resource Sharing (CORS) is a web standard enforced by browsers to prevent malicious scripts on one origin from accessing sensitive data on another origin without authorization.

Case Study: Dashboard Fetch Failures

A development team split their monolith into a frontend app (app.local) and an API backend (api.local). However, the browser blocked all dashboard queries, throwing CORS policy errors. The team tried adding wildcards, which broke credentials validation.

The Bug: Incompatible Headers

To resolve the CORS block, the developers added wildcards, but also required cookie credentials for session validation:

Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

Browsers block this combination because a server cannot authorize credentialed requests from an untrusted, arbitrary origin.

The Fix: Dynamic Origin Verification

We updated the backend configuration to validate the request origin against a whitelist of trusted domains, echoing that origin back dynamically:

$allowed_origins = [
    'https://app.local',
    'https://admin.local'
];

$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

if (in_array($origin, $allowed_origins)) {
    header("Access-Control-Allow-Origin: " . $origin);
    header("Access-Control-Allow-Credentials: true");
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
    header("Access-Control-Allow-Headers: Content-Type, Authorization");
}

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header("HTTP/1.1 204 No Content");
    exit;
}

This dynamic reflection authorized credentialed requests securely without exposing the API to malicious origins.

Scroll to Top