Search code examples
phpreactjslaravelcorslaravel-10

Laravel 10 Cors Issue on React app from subdomain


Hi I am facing a very common issue yet can't solve which is cors issue in Laravel 10. I am trying to access from React app installed in subdomain. It seems the login is working fine but after authentication no other route is not working. Here is my cors config file:

'paths' => ['*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => false,

kernal.php

protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Illuminate\Http\Middleware\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

all code seems ok to me but not working and having issues:

admin:1 Access to XMLHttpRequest at 'https://example.xyz/api/admin/dashboard/' from origin 'https://demo.example.xyz' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

and headers on the network tab:

Request URL: https://example.xyz/api/admin/dashboard/ Referrer Policy: strict-origin-when-cross-origin


Solution

  • I have to first remove the trailing slash from the api url to get rid of from preflight issue and then needed to config the the cors.php config file as below:

    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    
    'allowed_methods' => ['*'],
    
    'allowed_origins' => ['*'],
    
    'allowed_origins_patterns' => [],
    
    'allowed_headers' => [':authority:', ':method:', ':path:', ':scheme:'], // this is the line i needed to update to solve the issue.
    
    'exposed_headers' => [],
    
    'max_age' => 0,
    
    'supports_credentials' => false,
    

    and worked like charm !!