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

Cors Bundle Laravel Package

coka/cors-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer:
    composer require coka/cors-bundle
    
  2. Enable the Bundle in config/bundles.php:
    CedrickOka\CorsBundle\CorsBundle::class => ['all' => true],
    
  3. Basic Configuration in config/packages/coka_cors.yaml:
    cors:
        paths:
            '^/api/*':
                allow_origin: ['*']
                allow_methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
                allow_headers: ['Content-Type', 'Authorization']
                expose_headers: []
                max_age: 3600
                allow_credentials: false
    
  4. First Use Case: Test CORS with a frontend request to /api/test. Verify headers in browser DevTools (Access-Control-Allow-Origin).

Implementation Patterns

Core Workflows

  1. Path-Based Configuration:

    • Define granular CORS rules per route prefix (e.g., /api/* vs /admin/*).
    • Example: Restrict /admin to specific origins:
      paths:
          '^/admin/*':
              allow_origin: ['https://trusted-domain.com']
      
  2. Dynamic Origin Handling:

    • Use environment variables for origins (e.g., ALLOWED_ORIGINS in .env):
      allow_origin: '%env(ALLOWED_ORIGINS)%'
      
    • Split into arrays:
      allow_origin: ['%env(ORIGIN_1)%', '%env(ORIGIN_2)%']
      
  3. Middleware Integration:

    • The bundle auto-registers as a Symfony middleware. Override in config/packages/coka_cors.yaml:
      middleware: ['cors']
      
  4. Custom Headers:

    • Extend expose_headers for non-standard responses (e.g., X-RateLimit-Limit):
      expose_headers: ['X-RateLimit-Limit', 'X-RateLimit-Remaining']
      
  5. Credentials Support:

    • Enable for authenticated requests:
      allow_credentials: true
      
    • Requires allow_origin to be explicit (not '*').

Advanced Patterns

  • Conditional Rules: Use Symfony’s when clause in config to apply rules based on environment:
    paths:
        '^/api/*':
            allow_origin: ['*']
            when: '%kernel.environment% in [dev, staging]'
    
  • Event-Based Extensions: Listen to kernel.response to modify CORS headers dynamically:
    // src/EventListener/CorsListener.php
    public function onKernelResponse(GetResponseForControllerResultEvent $event) {
        $response = $event->getResponse();
        $response->headers->set('Access-Control-Allow-Origin', 'https://dynamic-origin.com');
    }
    

Gotchas and Tips

Common Pitfalls

  1. Wildcard ('*') + Credentials Conflict:

    • Error: Access-Control-Allow-Origin cannot be '*' if allow_credentials: true.
    • Fix: Use explicit origins (e.g., ['https://app.example.com']).
  2. Preflight Requests (OPTIONS):

    • Issue: Missing OPTIONS method in allow_methods causes CORS failures for POST/PUT with custom headers.
    • Fix: Always include OPTIONS and ensure allow_headers matches frontend requests.
  3. Cache Headers:

    • Gotcha: max_age in seconds (e.g., 3600 = 1 hour). Set to 0 for dynamic origins.
    • Debug: Check Access-Control-Max-Age in response headers.
  4. Symfony 5.3+ Compatibility:

    • Warning: Bundle may not support Symfony’s latest middleware stack. Test with symfony/http-kernel ^5.3.
    • Workaround: Use framework.middleware in config/packages/coka_cors.yaml:
      framework:
          middleware:
              cors: CedrickOka\CorsBundle\Middleware\CorsMiddleware
      
  5. Debugging:

    • Tool: Use browser DevTools (Network tab) to inspect:
      • Access-Control-Allow-Origin (should match request origin).
      • Access-Control-Allow-Methods (verify methods are listed).
    • Logs: Enable Symfony’s profiler to see middleware execution order.

Extension Points

  1. Custom Middleware:

    • Extend CedrickOka\CorsBundle\Middleware\CorsMiddleware to add logic (e.g., IP-based origin whitelisting).
    • Example:
      use CedrickOka\CorsBundle\Middleware\CorsMiddleware as BaseCorsMiddleware;
      
      class CustomCorsMiddleware extends BaseCorsMiddleware {
          protected function getAllowedOrigins(): array {
              if ($this->isTrustedIP($this->request->getClientIp())) {
                  return ['https://trusted.com'];
              }
              return ['*'];
          }
      }
      
  2. Event Dispatching:

    • Subscribe to cors.pre_flight or cors.response events (if supported) to modify behavior dynamically.
  3. Configuration Overrides:

    • Use config/packages/override/coka_cors.yaml to merge settings without editing the main config.

Performance Tips

  • Minimize Headers: Only expose necessary headers in expose_headers to reduce payload size.
  • Cache Preflight: Set max_age to a high value (e.g., 86400 for 24h) for static APIs.
  • Environment-Specific Rules: Disable CORS in production for internal APIs:
    when: '%kernel.environment% != prod'
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle