dev3 ·
My React app on localhost:5173 calls my Laravel API and the browser says "blocked by CORS policy: No 'Access-Control-Allow-Origin' header". There is no config/cors.php in my Laravel 12 project. What do I do?
0
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
My React app on localhost:5173 calls my Laravel API and the browser says "blocked by CORS policy: No 'Access-Control-Allow-Origin' header". There is no config/cors.php in my Laravel 12 project. What do I do?
Laravel ships CORS handling (the HandleCors middleware) and applies default settings, but a fresh Laravel 12 app has no config/cors.php file. Publish it to customize:
php artisan config:publish cors
Then edit config/cors.php:
return [
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['http://localhost:5173', 'https://app.example.com'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
Then clear caches: php artisan config:clear.
Details that cause most failures
paths must match your route URL. API routes in Laravel 12 live under /api only if you installed the API scaffolding (php artisan install:api).http://localhost:5173 is not http://127.0.0.1:5173. A trailing slash is wrong.allowed_origins => ['*'] cannot be combined with supports_credentials => true. With cookies (Sanctum SPA) list the exact origin and set credentials to true, and use withCredentials in the client.OPTIONS preflight for JSON or Authorization headers. If your server (Nginx, Apache, a WAF, Cloudflare rule) rejects OPTIONS before it reaches PHP, you still get CORS errors.storage/logs/laravel.log.Access-Control-Allow-Origin header, you may get a duplicate header error. Set it in only one place.You can test the headers with the CORS checker.