DEV3 Technologies home

DEV3 Developer Forum

How do I fix CORS errors for my Laravel 12 API?

Laravel helpSolved0 views
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?

#laravel#cors#api

0

1 reply

dev3 · Accepted answer

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).
  • Origins must match exactly: scheme, host and port. 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.
  • The browser sends an 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.
  • A 500 error response from your app also lacks CORS headers, so the real error is hidden behind the CORS message. Check the Network tab and storage/logs/laravel.log.
  • If your hosting adds its own 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.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.