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:
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.
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)bashphp artisan config:publish cors2Configure Explicit Vite Origins, Methods, and Headers
config/cors.phpReplace 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, ];3Define FRONTEND_URL Without a Trailing Slash and Clear Config Cache
.envBrowser 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.
.envdotenvAPP_URL=http://localhost:8000 FRONTEND_URL=http://localhost:5173 # Then run: # php artisan config:clear4Use Consistent API Base URLs and JSON Headers in React (Vite)
src/lib/apiClient.tsEnsure 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.tstypescriptconst 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.
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.
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.
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.
Deploying Behind Nginx? Eliminate CORS Preflights or Configure Your 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).
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.
Related CORS Stack Simulators
Browse all 12 stacks →Laravel Sanctum SPA Cookie Auth CORS Simulator & Fix Guide
Fix Laravel Sanctum SPA cookie CORS errors. Validate supports_credentials, SANCTUM_STATEFUL_DOMAINS, X-XSRF-TOKEN preflight headers, and SameSite rules.
Laravel API + Next.js App Router CORS Simulator & Fix Guide
Debug CORS between Laravel 11/12 APIs and Next.js App Router on port 3000. Separate Server Component fetches from Client Component browser preflights.
FastAPI + React (Vite) CORS Config Simulator & Fix Guide
Simulate and resolve CORS errors between Python FastAPI and React Vite on port 5173. Fix preflight OPTIONS failures, Pydantic 422 responses, and upload headers.
Node.js Express + React (Vite) CORS Config Simulator & Fix Guide
Resolve CORS preflight errors between Node.js Express APIs and React Vite on port 5173. Generate cors() configs, fix PATCH/DELETE methods, and debug headers.