3

I am currently working with Laravel 12.13 and facing an issue with CORS. I have configured the HandleCors middleware and the CORS settings in my application, but I am still getting CORS errors when trying to make requests from the frontend to the backend.

Here's what I have done so far:

In bootstrap/app.php, I have added the following middleware configuration:

<?php use Illuminate\Foundation\Application; 
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware; 
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
    web: __DIR__.'/../routes/web.php',
    api: __DIR__.'/../routes/api.php',
    commands: __DIR__.'/../routes/console.php',
    health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
    // Register native CORS middleware in Laravel 12
    $middleware->append(\Illuminate\Http\Middleware\HandleCors::class);

    // You can add other global middleware here
})
->withExceptions(function (Exceptions $exceptions) {
    //
})
->create();

I have created the cors.php configuration file inside the config directory with the following content:

<?php
return [
'paths' => ['api/v1/*'],
// Methods I want to allow for CORS:
'allowed_methods' => ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE'],
// Origins from where I allow access without CORS interference:
'allowed_origins' => ['https://annaponsprojects.com'],

'allowed_origins_patterns' => [],

// Headers I want to allow to receive in frontend requests:
'allowed_headers' => ['Content-Type', 'Authorization', 'Accept'],

'exposed_headers' => [],
// Don't perform preflight until 1 hour has passed:
'max_age' => 3600,
// Indicates if the browser can send cookies (works with tokens):
'supports_credentials' => false ];

However, I am still encountering CORS issues when sending a request from the frontend to my backend API. The error message I receive is:

Access to fetch at '' from origin '' 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.

What have I tried so far? I’ve made sure to include the correct middleware (HandleCors) in the bootstrap/app.php.

I’ve configured CORS settings in the config/cors.php file.

I’ve cleared the cache (php artisan config:clear and php artisan cache:clear).

What could I be missing? I suspect the issue might be related to the CORS configuration, but I am not sure. Is there anything else I should check or configure in Laravel 12.13 to resolve this issue?

1
  • No worries, I just spent about two hours trying to solve this with no luck, so you're not alone! Commented May 26 at 21:37

2 Answers 2

4

Put the CORS middleware in front of everything, start with an open-access config, purge cache, test, and secure the rules afterwards.

bootstrap/app.php:

use Illuminate\Http\Middleware\HandleCors;
use Illuminate\Foundation\Configuration\Middleware;

->withMiddleware(function (Middleware $middleware) {
    // run CORS before everything else
    $middleware->prepend(HandleCors::class);
});

config/cors.php:

return [
    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    'allowed_methods'   => ['*'],
    'allowed_origins'   => [
        'https://annaponsprojects.com',
        'http://localhost:5173',
    ],
    'allowed_origins_patterns' => [
        '/^https?:\/\/([a-z0-9-]+\.)?annaponsprojects\.com$/',
    ],
    'allowed_headers'   => ['*'],
    'exposed_headers'   => [],
    'max_age'           => 3600,
    'supports_credentials' => false,
];

Execute php artisan optimize:clear and restart PHP-FPM to implement the new configuration. Test with a plain curl -I -X OPTIONS to make sure Access-Control-Allow-Origin and the rest of the headers appear. Now that the headers are there and the browser is happy, replace the wildcards with the actual methods, headers, and origins that you actually require.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for your help! Your response was exactly what I needed to solve the problem. Placing the CORS middleware at the beginning was crucial and made everything work properly. I followed your instructions with the open-access configuration, purged the cache, and tested it with the curl command. Everything is working great now, and I’ll secure the rules as suggested. Thanks again for your support!
0
  1. In bootstrap/app.php, you must register the middleware using appendToGroup() for api, not just append() globally
->withMiddleware(function (Middleware $middleware) {
    $middleware->appendToGroup('api', \Illuminate\Http\Middleware\HandleCors::class);
})
  1. In config/cors.php, make sure the 'paths' entry includes your full API path prefix:
'paths' => ['api/*'],
  1. Ensure your allowed_origins exactly match the request origin (e.g, include protocol: https://annaponsprojects.com).

Fixing all of above, you have to clear and cache your config again, for that use below bash commands as well as make sure no web server (like Nginx or Apache) is stripping or blocking CORS headers.

php artisan config:clear
php artisan cache:clear
php artisan config:cache

After these steps, CORS should work correctly. If not, double-check that the frontend request is actually hitting your Laravel backend and not being blocked by a proxy or network issue.

additionally you can refere their doc https://laravel.com/docs/12.x/middleware

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.