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

Auto Preflight Bundle Laravel Package

benkle/auto-preflight-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require benkle/auto-preflight-bundle
    
  2. Register the Bundle Add to config/app.php under providers:

    Benkle\AutoPreflightBundle\BenkleAutoPreflightBundle::class,
    

    And to config/app.php under aliases:

    'AutoPreflight' => Benkle\AutoPreflightBundle\Facades\AutoPreflight::class,
    
  3. Configure CORS Add to config/cors.php (or create if missing):

    'paths' => ['api/*'],
    'allowed_methods' => ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    'allowed_origins' => ['*'],
    'allowed_headers' => ['x-auth-token', 'content-type'],
    
  4. First Use Case Define a route with methods explicitly (e.g., POST):

    Route::post('/api/resource', [ResourceController::class, 'store'])
        ->methods(['POST', 'OPTIONS']); // <-- Critical for preflight
    

    Test with a curl preflight request:

    curl -X OPTIONS -H "Origin: http://example.com" -H "Access-Control-Request-Method: POST" http://your-app.test/api/resource
    

Implementation Patterns

Workflow Integration

  1. Route Definition Always include OPTIONS in the methods array for API routes:

    Route::post('/api/data', [DataController::class, 'create'])
        ->methods(['POST', 'OPTIONS']);
    
    • Why? The bundle only intercepts OPTIONS requests if explicitly allowed.
  2. Dynamic Configuration Override default CORS settings per route using middleware:

    Route::middleware(['cors:custom'])->post('/api/admin', [AdminController::class, 'store']);
    

    Define custom in config/cors.php:

    'custom' => [
        'allowed_origins' => ['https://admin.example.com'],
        'allowed_headers' => ['authorization', 'x-api-key'],
    ],
    
  3. Facade Usage Manually trigger preflight responses (rarely needed):

    use Benkle\AutoPreflightBundle\Facades\AutoPreflight;
    
    public function customPreflight()
    {
        return AutoPreflight::respond([
            'allow_origin' => 'https://trusted.com',
            'allow_methods' => ['GET', 'POST'],
        ]);
    }
    
  4. Middleware Stack Ensure AutoPreflightMiddleware runs before your API middleware:

    $kernel->pushMiddlewareToGroup('api', \Benkle\AutoPreflightBundle\Http\Middleware\AutoPreflightMiddleware::class);
    

Gotchas and Tips

Pitfalls

  1. Missing OPTIONS Method

    • Symptom: Preflight requests return 405 Method Not Allowed.
    • Fix: Add OPTIONS to route methods() array.
      Route::post('/endpoint')->methods(['POST', 'OPTIONS']);
      
  2. Configuration Overrides

    • Issue: Bundle settings in config/cors.php may conflict with Symfony’s native CORS.
    • Solution: Disable Symfony’s CORS middleware if using this bundle:
      // config/bundles.php
      Symfony\WebServerBundle\WarmupBundle::class => ['all' => true],
      // Remove Symfony\Bundle\FrameworkBundle\HttpCache\HttpCacheBundle if present
      
  3. Header Injection Quirks

    • Problem: allow_headers is treated as a comma-separated string, not an array.
      # config/cors.php
      allowed_headers: 'content-type,x-auth-token,X-Custom-Header'
      
    • Workaround: Escape commas if dynamically setting headers via code.
  4. Caching Headers

    • Gotcha: Preflight responses may be cached by proxies (e.g., Nginx, Cloudflare).
    • Fix: Add Vary: Origin to preflight responses:
      // In AutoPreflightMiddleware
      $response->headers->set('Vary', 'Origin');
      

Debugging Tips

  1. Log Preflight Requests Add to AutoPreflightMiddleware:

    \Log::debug('Preflight request', [
        'origin' => $request->headers->get('Origin'),
        'method' => $request->headers->get('Access-Control-Request-Method'),
    ]);
    
  2. Validate Headers Use dd() to inspect headers in a controller:

    public function __invoke(Request $request)
    {
        dd($request->headers->all());
    }
    
  3. Test with Postman

    • Set Method: OPTIONS.
    • Add headers:
      Origin: http://example.com
      Access-Control-Request-Method: POST
      Access-Control-Request-Headers: x-auth-token
      

Extension Points

  1. Custom Response Logic Override the middleware class:

    // app/Http/Middleware/CustomPreflightMiddleware.php
    namespace App\Http\Middleware;
    
    use Benkle\AutoPreflightBundle\Http\Middleware\AutoPreflightMiddleware as BaseMiddleware;
    
    class CustomPreflightMiddleware extends BaseMiddleware
    {
        protected function getAllowedMethods(): array
        {
            return ['GET', 'POST', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'];
        }
    }
    

    Register it in AppServiceProvider:

    public function boot()
    {
        $this->app->bind(
            \Benkle\AutoPreflightBundle\Http\Middleware\AutoPreflightMiddleware::class,
            \App\Http\Middleware\CustomPreflightMiddleware::class
        );
    }
    
  2. Event Listeners Listen for preflight events (if the bundle emits them):

    // config/events.php
    'Benkle\AutoPreflightBundle\Events\PreflightHandled' => [
        \App\Listeners\LogPreflight::class,
    ],
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky