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

Bff Proxy Bundle Laravel Package

danielburger1337/bff-proxy-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require danielburger1337/bff-proxy-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        DanielBurger1337\BffProxyBundle\BffProxyBundle::class => ['all' => true],
    ];
    
  2. Configure Upstream Services Define your upstream services in config/packages/bff_proxy.yaml:

    bff_proxy:
        upstreams:
            api-gateway:
                http_client: "@http_client"
                request_factory: "@psr17_factory"
                stream_factory: "@psr17_factory"
                http_foundation_factory: "@psr7_to_httpfoundation_bridge"
    
  3. Route Proxy Requests Use the bff_proxy route attribute to proxy requests to an upstream:

    // src/Controller/ProxyController.php
    use DanielBurger1337\BffProxyBundle\Attribute\BffProxy;
    
    #[Route('/api/{path}', name: 'bff_proxy', methods: ['GET', 'POST'])]
    #[BffProxy(upstream: 'api-gateway')]
    public function proxy(Request $request, string $path): Response
    {
        return new Response(); // Handled by the bundle
    }
    

First Use Case

Proxy a frontend request to an internal API while preserving headers:

# config/packages/bff_proxy.yaml
bff_proxy:
    upstreams:
        internal-api:
            http_client: "@http_client"
            passthrough_request_headers: ["Authorization", "X-Forwarded-For"]

Implementation Patterns

Workflow: Proxying Requests

  1. Define Upstream Services Configure each upstream service with its HTTP client and header passthrough rules:

    bff_proxy:
        upstreams:
            auth-service:
                http_client: "@auth_http_client"
                passthrough_request_headers: ["Authorization"]
    
  2. Annotate Routes Use the #[BffProxy] attribute to mark routes for proxying:

    #[Route('/auth/{endpoint}', name: 'auth_proxy')]
    #[BffProxy(upstream: 'auth-service')]
    public function authProxy(Request $request, string $endpoint): Response
    {
        return new Response(); // Proxy logic handled by bundle
    }
    
  3. Dynamic Upstream Selection Use the options_parameter to dynamically select upstreams at runtime:

    bff_proxy:
        options_parameter: upstream
    
    curl /api/data?upstream=analytics-service
    

Integration Tips

  • Laravel-Specific Setup For Laravel, use Symfony’s HTTP client bridge (e.g., symfony/http-client) and configure it in config/services.php:

    'http_client' => fn () => new \Symfony\Contracts\HttpClient\HttpClient(),
    
  • Middleware Integration Add middleware to modify requests before proxying:

    use DanielBurger1337\BffProxyBundle\Event\BffProxyEvent;
    
    public function onProxy(BffProxyEvent $event): void
    {
        $event->getRequest()->headers->set('X-Custom-Header', 'value');
    }
    

    Register it in EventDispatcher:

    $dispatcher->addListener(BffProxyEvents::ON_PROXY, [$this, 'onProxy']);
    
  • Local Proxy for Development Enable local proxying to bypass upstreams during development:

    bff_proxy:
        local_proxy: true
    

Gotchas and Tips

Pitfalls

  1. Header Passthrough Conflicts

    • Issue: Headers like Host or Content-Length may be overwritten by the proxy.
    • Fix: Explicitly whitelist headers in passthrough_request_headers and avoid passthrough_request_x_headers: true.
  2. CORS and Security Headers

    • Issue: Upstream responses may lack CORS headers, causing frontend errors.
    • Fix: Use middleware to inject CORS headers after proxying:
      $response->headers->set('Access-Control-Allow-Origin', '*');
      
  3. Breaking Changes in Minor Versions

    • Issue: Versions 0.2.0+ and 0.3.0+ introduced breaking changes (e.g., removed BffProxyVoter).
    • Fix: Review changelogs and update configurations accordingly.
  4. Performance Overhead

    • Issue: Proxying adds latency due to HTTP client overhead.
    • Fix: Reuse HTTP clients and avoid unnecessary header passthrough.

Debugging

  • Log Proxy Requests Enable debug mode in config/packages/monolog.yaml to log proxy events:

    handlers:
        main:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%.log"
            level: debug
    
  • Inspect Events Use the BffProxyEvents::ON_PROXY event to debug request/response transformations:

    $dispatcher->addListener(BffProxyEvents::ON_PROXY, function (BffProxyEvent $event) {
        \Log::debug('Proxy Request:', [
            'uri' => $event->getRequest()->getUri(),
            'headers' => $event->getRequest()->headers->all(),
        ]);
    });
    

Extension Points

  1. Custom HTTP Clients Extend the bundle by creating custom HTTP clients for specific upstreams:

    upstreams:
        custom-service:
            http_client: "@custom.http_client"
    
    // src/HttpClient/CustomHttpClient.php
    class CustomHttpClient extends \Symfony\Contracts\HttpClient\HttpClient
    {
        public function request(string $method, string $url, array $options = []): ResponseInterface
        {
            // Custom logic (e.g., retry, timeout)
            return parent::request($method, $url, $options);
        }
    }
    
  2. Response Modification Subscribe to BffProxyEvents::ON_RESPONSE to modify responses:

    $dispatcher->addListener(BffProxyEvents::ON_RESPONSE, function (BffProxyEvent $event) {
        $response = $event->getResponse();
        $response->headers->set('X-Processed-By', 'BFF-Proxy');
    });
    
  3. Dynamic Upstream Routing Use the options_parameter to route requests dynamically:

    bff_proxy:
        options_parameter: service
    
    curl /data?service=analytics
    

Configuration Quirks

  • Boolean Values in YAML Use true/false (not yes/no) for boolean flags like local_proxy:

    bff_proxy:
        local_proxy: false  # Disables local proxy
    
  • PSR Factories Ensure your request_factory, stream_factory, and http_foundation_factory are PSR-17 compliant (e.g., nyholm/psr7):

    upstreams:
         api:
             request_factory: "@psr17_factory"
             stream_factory: "@psr17_factory"
    
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