allow cross domain ajax requests

allow cross domain ajax requests

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Allow Cross-Domain AJAX Requests: Security and Best Practices

Allowing external domains to make AJAX requests to your API is a common requirement for integrations, but the approach taken by adding Access-Control-Allow-Origin: * and Access-Control-Allow-Methods: GET, POST at the top of a script is dangerous. This specific implementation exposes your application to Cross-Site Request Forgery (CSRF) attacks and does not handle the complexities of the CORS specification correctly.

While the code snippet you referenced sets basic headers, it fails to address preflight requests and lacks critical security constraints. When a browser receives Access-Control-Allow-Origin: *, it essentially tells any web page on the internet that your API endpoints are public. This is fine for reading data (GET requests), but highly risky for state-changing operations like POST or PUT unless you implement strict validation mechanisms.

The Missing Preflight Check

The most significant technical gap in the provided solution is the handling of preflight requests. Modern browsers enforce the CORS specification by checking the Access-Control-Allow-Origin header on every request. However, if a request includes custom headers (like Authorization: Bearer <token>) or uses methods not listed in Allow-Methods, the browser will automatically send an OPTIONS request before the actual data request.

The code snippet above ignores this entirely. If your script does not respond to OPTIONS requests with the appropriate headers, the browser will block the subsequent GET or POST request regardless of what your PHP (or other language) script sends back. The correct implementation must include logic to detect the request method and respond accordingly:

// Check for preflight requests first
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
    }
    
    // Allow specific headers requested by the client
    $allowed_headers = ['Authorization', 'Content-Type'];
    $headers_to_allow = '';
    foreach ($allowed_headers as $header) {
        $headers_to_allow .= ', ' . $header;
    }
    header("Access-Control-Allow-Headers: " . trim($headers_to_allow));
    
    // Allow the specific origin requested (or * if explicitly intended, but see below)
    header("Access-Control-Allow-Origin: *");
    
    // Cache preflight responses
    header("Access-Control-Max-Age: 86400");
}

The Danger of Wildcards

Using Access-Control-Allow-Origin: * is convenient for development and simple public APIs, but it creates a severe security vulnerability when combined with credentials. If you intend to send cookies or authentication tokens via AJAX, you must never use the wildcard. Instead, you should echo back the exact origin header sent by the browser:

$origin = $_SERVER['HTTP_ORIGIN'];
if ($origin) {
    header("Access-Control-Allow-Origin: $origin");
} else {
    header("Access-Control-Allow-Origin: *"); // Fallback only if no origin is set (e.g., curl requests)
}

If you use * while also sending credentials, the browser will simply ignore your headers and block the request. This inconsistency often leads to confusing debugging sessions where your API works perfectly when testing with Postman or cURL but fails silently in a browser extension or another domain.

Implementing CSRF Protection

Allowing cross-origin POST requests opens the door for CSRF attacks. If a user visits Site A (attacker), which has a malicious script on it, that script can send a POST request to your API at Site B (victim) without the user's knowledge. Since browsers automatically attach cookies to same-site requests, this can lead to unauthorized actions like changing passwords or making purchases.

To mitigate this, you must implement CSRF tokens for all state-changing operations. Even if you allow cross-origin traffic, the server must verify that the request originates from a trusted source or contains a valid token. This usually involves generating a token on the server side and expecting it in the request payload or header. Without this layer of defense, simply exposing your API to the world via CORS headers is insufficient.

Modern Frameworks Handle This Better

If you are building this application using Laravel, relying on raw header() calls scattered across multiple scripts is inefficient and error-prone. Laravel provides a robust middleware stack specifically designed for handling CORS correctly.

You can define a custom policy or use the built-in Cors middleware to handle these requirements globally. This ensures that preflight requests are handled consistently, headers are validated against your security policies, and you avoid repeating logic in every controller or script file. For more complex scenarios involving multiple domains or specific header restrictions, Laravel's configuration options allow you to fine-tune the behavior without reinventing the wheel.

Conclusion

The simple two-line header approach is a quick fix that fails under scrutiny. It ignores preflight requests, risks CSRF vulnerabilities, and creates inconsistent behavior when credentials are involved. A secure implementation requires handling OPTIONS requests explicitly, validating origins rather than using wildcards for authenticated endpoints, and enforcing CSRF tokens on state-changing operations. Leveraging framework-specific solutions like Laravel's CORS middleware is the most reliable path forward to maintain security without sacrificing functionality.

Our network