CORS & Preflight Simulator · Laravel 11/12 API + React (Vite)

Laravel + React (Vite) CORS Config Simulator & Fix Guide

Simulate Fetch Standard preflight (OPTIONS) triggers, credential rules, and origin matching between React (Vite) and Laravel 11/12 API. Copy generated configuration code below.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust stack settings or load a test scenario2. Inspect live diagnostics3. Copy generated config
Quick-Test Scenarios:

1. Browser Request (React (Vite))

2. Server Response Policy (Laravel 11/12 API)

Access-Control-Allow-Methods
<?php
// config/cors.php (Laravel 11/12 — run: php artisan config:publish cors)
// If using Laravel Sanctum SPA cookie auth, also set in .env:
// SANCTUM_STATEFUL_DOMAINS=localhost:5173
// SESSION_DOMAIN=localhost

return [
    'paths' => ['api/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],

    'allowed_origins' => ['http://localhost:5173'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['Content-Type', 'Authorization', 'Accept', 'X-Requested-With'],

    'exposed_headers' => [],

    'max_age' => 86400,

    'supports_credentials' => false,
];

Preflight (OPTIONS)

Triggered · Passed

Content-Type "application/json" is not CORS-safelisted (only application/x-www-form-urlencoded, multipart/form-data, and text/plain avoid preflight). Request includes non-safelisted header(s): Authorization, X-Requested-With.

Browser Verdict

Allowed

Browser CORS validation passed. JavaScript can read the response body.

Rule Engine Diagnostics

  • Reverse Proxy Tip: Avoid Duplicate CORS Headers in Nginx + Upstream App

    Never configure Access-Control-Allow-Origin in both Nginx and your backend framework simultaneously. Browsers reject duplicate headers with: "The 'Access-Control-Allow-Origin' header contains multiple values '*, http://localhost:5173', but only one is allowed." Choose one layer (or use proxy_hide_header in Nginx).

Simulated HTTP Response Headers

HTTP/1.1
Preflight (OPTIONS)
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: http://localhost:5173
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization, Accept, X-Requested-With
Access-Control-Max-Age: 86400
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
Actual Response (POST)
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://localhost:5173
Vary: Origin

Runs locally in your browser. Origins, endpoints, and headers are never sent to a server.

Typical Browser Console Error (React (Vite) → Laravel 11/12 API)

When cross-origin headers are missing, mismatched, or blocked during preflight between React (Vite) and Laravel 11/12 API, Chrome and Firefox log an error matching the pattern below in DevTools:

DevTools Console Output

Access to fetch at 'http://localhost:8000/api/v1/projects' 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.

Why CORS Blocks Requests Between React (Vite) and Laravel 11/12 API

When you pair a Laravel 11 or Laravel 12 backend running via php artisan serve on http://localhost:8000 (or Laravel Herd and Valet on a local .test hostname) with a React single-page application served by Vite on http://localhost:5173, the browser classifies every API call as cross-origin because the port or hostname differs. Under the WHATWG Fetch Standard, the browser attaches an Origin: http://localhost:5173 request header and strictly validates the response before exposing any JSON payload, status body, or custom header to your React components.

In Laravel 11 and 12, the streamlined application skeleton no longer publishes config/cors.php into your repository by default. Instead, Laravel loads internal fallback defaults from the framework vendor directory where paths only match api/* and sanctum/csrf-cookie, and allowed_origins defaults to wildcard *. The moment your React Vite app sends an Authorization: Bearer token, a custom header such as X-Requested-With, or a JSON POST, PUT, PATCH, or DELETE request, the browser automatically issues an HTTP OPTIONS preflight request before your Laravel controller ever executes.

If your API routes live outside the api/* prefix, if you enable credentials while allowed_origins still holds *, or if an unhandled PHP exception (HTTP 500) bypasses Laravel's HandleCors middleware during local development, Chrome and Firefox report a misleading CORS failure even though the underlying cause was either a missing config/cors.php publish step, a route prefix mismatch, or a crashing controller. Checking the exact OPTIONS request and response headers in DevTools alongside a deterministic rule simulator isolates these issues in seconds.

Step-by-Step Laravel 11/12 API + React (Vite) CORS Fix Guide

Follow each step below in order to eliminate preflight failures and lock down production origins safely for Laravel 11/12 API.

  1. 1Publish the Laravel CORS Configuration File

    terminal (project root)

    Laravel 11 and 12 ship with HandleCors registered globally in the HTTP kernel, but the configuration file stays hidden inside vendor until published. Run the Artisan publish command so you can explicitly whitelist your Vite origin, REST methods, and custom headers under version control across local, staging, and production environments.

    terminal (project root)bash
    php artisan config:publish cors
  2. 2Configure Explicit Vite Origins, Methods, and Headers

    config/cors.php

    Replace the permissive wildcard origin with an environment-driven list containing http://localhost:5173 for development and your production React domain. Explicitly include Authorization, Accept, X-Requested-With, and Content-Type so JSON preflight checks succeed reliably across Chrome, Firefox, and Safari without depending on inconsistent wildcard behavior.

    config/cors.phpphp
    <?php
    
    return [
        'paths' => ['api/*', 'sanctum/csrf-cookie'],
    
        'allowed_methods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
    
        'allowed_origins' => array_filter([
            env('FRONTEND_URL', 'http://localhost:5173'),
        ]),
    
        'allowed_origins_patterns' => [],
    
        'allowed_headers' => ['Content-Type', 'Authorization', 'Accept', 'X-Requested-With'],
    
        'exposed_headers' => ['X-RateLimit-Remaining'],
    
        'max_age' => 86400,
    
        'supports_credentials' => false,
    ];
  3. 3Define FRONTEND_URL Without a Trailing Slash and Clear Config Cache

    .env

    Browser Origin headers never include a trailing slash. Putting http://localhost:5173/ in .env causes an exact string comparison failure inside Laravel's HandleCors middleware. After updating .env, clear any cached configuration so the new origin takes effect immediately in both Artisan serve and Octane workers.

    .envdotenv
    APP_URL=http://localhost:8000
    FRONTEND_URL=http://localhost:5173
    
    # Then run:
    # php artisan config:clear
  4. 4Use Consistent API Base URLs and JSON Headers in React (Vite)

    src/lib/apiClient.ts

    Ensure your React fetch wrapper targets http://localhost:8000 consistently rather than mixing localhost and 127.0.0.1. Always include Accept: application/json so Laravel returns structured 401 and 422 JSON responses instead of 302 redirects to /login, which trigger cross-origin redirect errors in the browser.

    src/lib/apiClient.tstypescript
    const API_BASE = import.meta.env.VITE_API_URL ?? 'http://localhost:8000';
    
    export async function createProject(token: string, payload: { name: string }) {
      const response = await fetch(`${API_BASE}/api/v1/projects`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Accept: 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(payload),
      });
    
      if (!response.ok) {
        throw new Error(`API error: ${response.status}`);
      }
    
      return response.json();
    }

Common Laravel 11/12 API + React (Vite) CORS Pitfalls

Even when your basic origin string looks correct, these three framework-specific edge cases frequently reintroduce CORS failures in staging and production environments.

Pitfall 1

Laravel 302 Redirects to /login Masquerading as CORS Errors

When a React Vite fetch request omits the Accept: application/json header and hits an auth:sanctum protected endpoint with an expired or missing token, Laravel's exception handler responds with a 302 redirect to /login. Because /login is not listed in config/cors.php paths, the browser rejects the redirected response and prints a CORS error instead of HTTP 401.

Pitfall 2

Mixing localhost and 127.0.0.1 Between Vite and config/cors.php

Vite may bind to http://localhost:5173 while developers sometimes open http://127.0.0.1:5173 in the browser. To the browser Same-Origin Policy, localhost and 127.0.0.1 are completely distinct hosts. If allowed_origins only permits http://localhost:5173, requests from http://127.0.0.1:5173 will be blocked.

Pitfall 3

Stale Config Cache After Changing .env Values

Running php artisan config:cache in staging or local Docker containers locks the old FRONTEND_URL into bootstrap/cache/config.php. Subsequent edits to .env or config/cors.php are silently ignored until you run php artisan config:clear and restart queue or Octane workers.

Related Tool · Same-Origin Reverse Proxy

Configure TLS, WebSocket headers, and X-Forwarded-Proto, or serve your frontend and /api/ on the same origin with Nginx Config for React (Vite) SPA + Same-Origin /api/ Proxy (Zero CORS).

Open Nginx Builder

Frequently Asked Questions

Should I use Vite server.proxy instead of configuring Laravel CORS?
Vite's server.proxy option is convenient for local development because it tunnels /api requests through port 5173 so the browser treats them as same-origin. However, Vite's dev server does not exist in production builds. If your production React bundle is hosted on Cloudflare Pages, Vercel, or an S3 bucket on a different origin from your Laravel API, you still must configure config/cors.php accurately and test cross-origin preflights locally.
Why does Laravel return a CORS error only when my controller throws a 500 error?
Fatal PHP syntax errors, out-of-memory crashes, or web server timeouts (such as Nginx 502 Bad Gateway) terminate execution before Laravel's HandleCors middleware can attach Access-Control-Allow-Origin headers to the response. Inspect the Network tab status code and storage/logs/laravel.log whenever a previously working endpoint suddenly reports a CORS failure.
How do I create config/cors.php in Laravel 11 or 12?
Run php artisan config:publish cors in your Laravel project root. Laravel 11 and 12 ship with built-in first-party CORS middleware (Illuminate\Http\Middleware\HandleCors) out of the box without any third-party Composer package, and publishing config/cors.php exposes paths, allowed_origins, allowed_methods, and supports_credentials for customization.
Can I allow multiple Vite preview and production origins in config/cors.php?
Yes. Populate allowed_origins with an array of explicit origins (for example, exploding a comma-separated CORS_ALLOWED_ORIGINS environment variable) or use allowed_origins_patterns with anchored regular expressions for preview subdomains. Never rely on wildcard * if your app later enables cookies or supports_credentials.
Browse all 12 stacks →