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

nelmio/cors-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nelmio/cors-bundle
    
    • No manual bundle registration needed if using Symfony Flex (v4.1+). For older versions, add to config/bundles.php:
      Nelmio\CorsBundle\NelmioCorsBundle::class => ['all' => true],
      
  2. Basic Configuration:

    • Override default settings in config/packages/nelmio_cors.yaml:
      nelmio_cors:
          paths:
              '^/api/*':
                  allow_origin: ['*']
                  allow_methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']
                  allow_headers: ['Content-Type', 'Authorization']
                  expose_headers: ['Link']
                  max_age: 3600
      
  3. First Use Case:

    • Test CORS headers on an API endpoint (/api/test). Use browser DevTools (Network tab) or curl -I to verify headers like:
      Access-Control-Allow-Origin: *
      Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
      

Implementation Patterns

Common Workflows

  1. API-Only CORS:

    • Restrict CORS to API routes only (e.g., /api/*) while excluding frontend assets:
      paths:
          '^/api/*': { allow_origin: ['*'] }
          '^/assets/*': ~  # Explicitly disable CORS for static files
      
  2. Dynamic Origin Whitelisting:

    • Use environment variables or runtime logic (e.g., allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']).
    • For dynamic values, use a path resolver (advanced):
      paths:
          '^/user/*':
              allow_origin: ['%kernel.environment%']
              allow_origin_resolver: ~  # Custom resolver class
      
  3. Preflight Handling:

    • Nelmio auto-handles OPTIONS requests. For custom logic, create an event subscriber:
      use Nelmio\CorsBundle\Event\PreflightEvent;
      
      public function onPreflight(PreflightEvent $event) {
          $event->setAllowedMethods(['GET', 'POST']);
      }
      
  4. Symfony Messenger Integration:

    • If using Messenger, ensure CORS is configured for async endpoints (e.g., /_symfony_messenger):
      paths:
          '^/_symfony_messenger': { allow_origin: ['*'] }
      
  5. Static File Handling:

    • For static files (e.g., /build/*), configure CORS at the web server level (Nginx/Apache) or use a middleware:
      // src/Kernel.php
      $kernel->add(new Nelmio\CorsBundle\Middleware\CorsMiddleware($this));
      

Integration Tips

  • Merge Configs: Use imports to split configs (e.g., dev.yaml, prod.yaml):
    imports:
        - { resource: nelmio_cors.yaml }
        - { resource: nelmio_cors.dev.yaml }
    
  • Event-Driven Extensions: Extend via nelmio_cors.event_listener or nelmio_cors.event_subscriber in services.yaml.
  • Testing: Use nelmio_cors.tester to assert CORS headers in PHPUnit:
    $this->assertCorsHeaders(['Access-Control-Allow-Origin' => '*']);
    

Gotchas and Tips

Pitfalls

  1. Static Files:

    • Issue: Nelmio does not modify headers for static files (e.g., /build/js/app.js). These must be configured in your web server.
    • Fix: Use .htaccess (Apache) or Nginx add_header directives:
      location /build/ {
          add_header 'Access-Control-Allow-Origin' '*';
          add_header 'Access-Control-Allow-Methods' 'GET';
      }
      
  2. Path Matching:

    • Issue: Regex paths are case-sensitive and must match the full URL (e.g., '^/api/v1/*' vs '^/api/*').
    • Fix: Use ^ and $ anchors for precision:
      paths:
          '^https://example.com/api/*': { ... }  # Full URL matching
      
  3. Caching Headers:

    • Issue: max_age in CORS preflight responses can cause stale caches if origins change.
    • Fix: Set max_age: 0 in development or use short TTLs (e.g., 300).
  4. Symfony Flex Conflicts:

    • Issue: Manual bundle registration may conflict with Flex auto-config.
    • Fix: Remove from bundles.php if using Flex (v4.1+).
  5. Event Order:

    • Issue: Custom event subscribers may run after Nelmio’s default logic.
    • Fix: Prioritize subscribers with tags:
      tags:
          - { name: kernel.event_subscriber, priority: 255 }  # Highest priority
      

Debugging

  • Check Headers: Use curl -I http://example.com/api/test or browser DevTools.
  • Log Events: Enable debug mode and log Nelmio\CorsBundle\Event\CorsEvent:
    monolog:
        handlers:
            cors:
                type: stream
                path: "%kernel.log_dir%/cors.log"
                channels: ["cors"]
    
  • Validate Config: Use Symfony’s config validator:
    php bin/console debug:config nelmio_cors
    

Extension Points

  1. Custom Resolvers:

    • Implement Nelmio\CorsBundle\Resolver\OriginResolverInterface for dynamic origins (e.g., JWT-based):
      class AuthOriginResolver implements OriginResolverInterface {
          public function resolve(array $config, ServerRequestInterface $request): array {
              return ['https://trusted-domain.com'];
          }
      }
      
    • Register in services.yaml:
      Nelmio\CorsBundle\Resolver\OriginResolverInterface: '@App\Resolver\AuthOriginResolver'
      
  2. Middleware Override:

    • Replace the default middleware in Kernel.php:
      $kernel->add(new App\Middleware\CustomCorsMiddleware());
      
  3. Event Subscribers:

    • Subscribe to nelmio_cors.preflight or nelmio_cors.response:
      use Nelmio\CorsBundle\Event\PreflightEvent;
      
      public static function getSubscribedEvents() {
          return [
              PreflightEvent::class => 'onPreflight',
          ];
      }
      
  4. Environment-Specific Configs:

    • Override paths per environment:
      # config/packages/nelmio_cors.dev.yaml
      nelmio_cors:
          paths:
              '^/api/*': { allow_origin: ['http://localhost:3000'] }
      
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui