I’m using Sanctum for authentication on Next.js. Some of my GET requests to Laravel were working fine, but others were failing due to CORS error:
Access to XMLHttpRequest at 'https://api.example.com/api/threads/single/thread_ID/?type=image-messages' from origin 'https://www.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
Here’s my cors.php file:
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
After much debugging, I discovered that the issue was caused by the query string at the end of the URL ?type=image-messages
. Routes without query parameters worked fine, but adding a query string triggered the CORS error. Question is why does it affect CORS handling even though I already set 'api/*'
.
Tried to update the CORS configuration to explicitly handle routes with query parameters by including a wildcard for query strings but it didn’t seem to work:
'paths' => ['api/*', 'api/threads/single/*{?}*']
I just gave up and revamped all my URLs that use query params.
I’m using Laravel 10.