Hi, I'm Mayone 👋

I'm a Web Developer and Entrepreneur

Tejiri Mayone

Hi, I'm Mayone 👋

I'm a Web Developer and Entrepreneur

Resolving CORS Issues in Laravel Sanctum on Shared Hosting

5 minutes
April 13, 2025
cors error with santum laravel PHP framework

cors error with santum laravel PHP framework

Hosting a Laravel application with Sanctum for API authentication on shared hosting can be challenging, especially when integrating a frontend on a different subdomain. This article explains how to configure Laravel Sanctum to handle Cross-Origin Resource Sharing (CORS) correctly, using a real-world example with the following .env settings:

APP_URL=https://api.weburladdr.com
FRONTEND_URL=https://app.weburladdr.com
SANCTUM_STATEFUL_DOMAINS=https://app.weburladdr.com
SESSION_DOMAIN=.weburladdr.com
SESSION_SECURE_COOKIE=true
SESSION_DRIVER=cookie

We’ll dive into a common CORS error, its causes, and a step-by-step solution tailored for shared hosting environments, ensuring secure API communication between https://api.weburladdr.com (backend) and https://app.weburladdr.com (frontend).

The Problem: CORS Error

When the frontend at https://app.weburladdr.com attempts to call the backend’s /login endpoint (https://api.weburladdr.com/login), you might encounter:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.weburladdr.com/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://app.weburladdr.com/’).

This error occurs because the browser’s Same Origin Policy restricts cross-origin requests unless the server explicitly allows the frontend’s origin via CORS headers (Access-Control-Allow-Origin). In this case, Laravel Sanctum’s configuration needs adjustment to permit https://app.weburladdr.com for stateful API requests.

Understanding the .env Configuration

Let’s break down the provided .env settings and their roles:

The CORS error suggests that SANCTUM_STATEFUL_DOMAINS or related CORS settings aren’t fully aligned, causing a mismatch in the Access-Control-Allow-Origin header.

Step-by-Step Solution

Here’s how to resolve the CORS issue on a shared hosting setup (e.g., with a Laravel project in /home/ourlordisgreat/laravel_server/ and public files in /home/ourlordisgreat/public_html/api.weburladdr.com/).

1. Verify .env Settings

Ensure the .env file is correct and includes the protocol (https://) for all URLs:

APP_URL=https://api.weburladdr.com
FRONTEND_URL=https://app.weburladdr.com
SANCTUM_STATEFUL_DOMAINS=https://app.weburladdr.com
SESSION_DOMAIN=.weburladdr.com
SESSION_SECURE_COOKIE=true
SESSION_DRIVER=cookie
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password

After updating .env, clear the configuration cache:

cd /home/ourlordisgreat/laravel_server
php artisan config:cache
php artisan cache:clear

2. Configure Laravel Sanctum

Sanctum handles CORS for stateful requests. Update the Sanctum configuration in config/sanctum.php:

return [
    'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'https://app.weburladdr.com')),
    'guard' => ['web'],
    'expiration' => null,
    'middleware' => [
        'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
        'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
    ],
];

3. Set Up CORS Configuration

Laravel uses the fruitcake/laravel-cors package or built-in CORS middleware for stateless API requests. Update config/cors.php:

return [
    'paths' => ['api/*', 'sanctum/*', 'login', 'logout', 'register'],
    'allowed_methods' => ['*'],
    'allowed_origins' => [env('FRONTEND_URL', 'https://app.weburladdr.com')],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,
];

4. Verify Middleware

Ensure Sanctum’s middleware is applied in app/Http/Kernel.php:

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
    'api' => [
        \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

The EnsureFrontendRequestsAreStateful middleware checks SANCTUM_STATEFUL_DOMAINS and sets CORS headers for stateful requests.

5. Update Frontend Requests

The frontend must handle Sanctum’s CSRF and cookie requirements. If using Axios (e.g., in a Vue/React app):

// Set withCredentials for cookies
axios.defaults.withCredentials = true;

// Fetch CSRF token before POST requests
axios.get('https://api.weburladdr.com/sanctum/csrf-cookie').then(() => {
    axios.post('https://api.weburladdr.com/login', {
        email: '[email protected]',
        password: 'password',
    }).then(response => {
        console.log('Login successful:', response);
    }).catch(error => {
        console.error('Login failed:', error);
    });
});

6. Configure Shared Hosting

Shared hosting environments require additional checks:

7. Test the Setup

  1. Clear Caches:

    php artisan config:cache
    php artisan cache:clear
    php artisan route:cache
    
  2. Verify CORS Headers:

    curl -I -X OPTIONS https://api.weburladdr.com/login
    

    Look for:

    Access-Control-Allow-Origin: https://app.weburladdr.com
    Access-Control-Allow-Credentials: true
    
  3. Test Login:

    From the frontend (https://app.weburladdr.com), trigger a login request. Use browser Dev Tools (Network tab) to confirm:

    • Request to https://api.weburladdr.com/sanctum/csrf-cookie sets cookies.
    • POST to /login returns 200 OK or expected response.
    • Headers include Access-Control-Allow-Origin: https://app.weburladdr.com.
  4. Check Logs:

    If errors persist, inspect:

    cat /home/ourlordisgreat/laravel_server/storage/logs/laravel.log
    

Troubleshooting Tips

If the CORS error remains, consider:

Additional Security Considerations

Conclusion

Configuring Laravel Sanctum for CORS on shared hosting requires precise .env settings, Sanctum and CORS configuration, and frontend adjustments. By setting SANCTUM_STATEFUL_DOMAINS=https://app.weburladdr.com, updating config/cors.php, and ensuring proper middleware, you can resolve the CORS error and enable secure communication between https://api.weburladdr.com and https://app.weburladdr.com. Shared hosting adds complexity, but with careful file permissions, SSL enforcement, and symlink management, your Laravel API can run smoothly.

For further issues, verify logs, test headers, and consult your hosting provider for server-specific quirks. Happy coding!


Tags: Laravel, Sanctum, CORS, Shared Hosting, API Authentication, Cross-Origin