Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Cors Laravel Package

barryvdh/laravel-cors

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require fruitcake/laravel-cors
    

    Publish the config file:

    php artisan vendor:publish --provider="Fruitcake\Cors\CorsServiceProvider" --tag="config"
    
  2. Basic Configuration: Edit config/cors.php to define allowed origins, methods, and headers. Example:

    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => false,
    
  3. First Use Case: Add the middleware to your app/Http/Kernel.php:

    protected $middleware = [
        \Fruitcake\Cors\HandleCors::class,
    ];
    

    Now, requests to routes under paths will automatically include CORS headers.


Implementation Patterns

Common Workflows

  1. Dynamic Origin Handling: Use allowed_origins_patterns for regex-based origin validation:

    'allowed_origins_patterns' => [
        '^https://(.*\.)?example\.com$',
        '^https://(.*\.)?client\.app$',
    ],
    
  2. Route-Specific CORS: Override CORS settings for specific routes via middleware groups:

    Route::middleware(['cors:api-only'])->group(function () {
        Route::get('/api/secure', function () {
            return response()->json(['data' => 'Secure']);
        });
    });
    

    Define api-only in config/cors.php:

    'groups' => [
        'api-only' => [
            'allowed_origins' => ['https://trusted-client.com'],
            'allowed_methods' => ['GET', 'POST'],
        ],
    ],
    
  3. Credentials Support: Enable CORS for credentials (cookies/auth headers) by setting:

    'supports_credentials' => true,
    

    Ensure Access-Control-Allow-Origin is explicit (not *).

  4. Preflight Requests: Handle OPTIONS requests dynamically by extending the middleware:

    Cors::addAllowedMethod('PATCH');
    Cors::addAllowedHeader('X-Custom-Header');
    
  5. Conditional CORS: Use middleware closures to conditionally apply CORS:

    Cors::addMiddleware(function ($request) {
        if ($request->user()?->isAdmin()) {
            return ['allowed_origins' => ['*']];
        }
        return [];
    });
    

Gotchas and Tips

Pitfalls

  1. Credentials Conflict:

    • supports_credentials: true requires explicit Access-Control-Allow-Origin (cannot use *).
    • Test with curl -X GET -H "Origin: https://client.com" --include --header "Cookie: session=...".
  2. Middleware Order:

    • Place HandleCors before SubstituteBindings or VerifyCsrfToken to avoid header overrides.
    • Example order in Kernel.php:
      protected $middleware = [
          \Fruitcake\Cors\HandleCors::class,
          \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
          // ...
      ];
      
  3. Path Matching:

    • paths uses Laravel’s router, so api/* matches /api/users but not /api/v1/users. Use:
      'paths' => ['api/v1/*', 'api/v2/*'],
      
    • For regex, use ~^(?!api/v1).+$~ in paths.
  4. Caching Headers:

    • max_age: 0 disables caching. Set to 86400 (1 day) for production:
      'max_age' => 86400,
      
  5. CSRF Token Conflicts:

    • If using Sanctum/Passport, ensure CORS allows sanctum/csrf-cookie and X-CSRF-TOKEN header:
      'paths' => ['sanctum/csrf-cookie'],
      'allowed_headers' => ['X-CSRF-TOKEN', 'Authorization'],
      

Debugging Tips

  1. Check Headers: Use dd($request->headers) or browser dev tools to verify Access-Control-* headers.

  2. Preflight Fails:

    • Ensure OPTIONS requests are handled (Laravel routes them by default).
    • Validate Access-Control-Request-Method and Access-Control-Request-Headers match your config.
  3. Dynamic Config: Override settings at runtime:

    Cors::setAllowedOrigins(['https://new-client.com']);
    
  4. Logging: Enable debug mode in config/cors.php:

    'debug' => env('APP_DEBUG', false),
    

    Logs CORS decisions to storage/logs/laravel.log.

Extension Points

  1. Custom Middleware: Extend HandleCors to add logic:

    namespace App\Http\Middleware;
    use Fruitcake\Cors\HandleCors as BaseCors;
    
    class CustomCors extends BaseCors {
        public function handle($request, Closure $next) {
            $this->cors->setAllowedOrigins([$request->input('origin')]);
            return parent::handle($request, $next);
        }
    }
    
  2. Event Listeners: Listen to cors.before and cors.after events in EventServiceProvider:

    protected $listen = [
        'cors.before' => [
            \App\Listeners\LogCorsRequest::class,
        ],
    ];
    
  3. API Resources: Attach CORS headers to API responses dynamically:

    return response()->json($resource)
        ->header('Access-Control-Expose-Headers', 'X-Custom-Header');
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime