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

Relay Proxy Bundle Laravel Package

dbp/relay-proxy-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   Add the bundle via Composer:
   ```bash
   composer require dbp/relay-proxy-bundle

Enable it in config/bundles.php:

return [
    // ...
    DigitalBlueprint\RelayProxyBundle\DbpRelayProxyBundle::class => ['all' => true],
];
  1. Configuration Publish the default config:

    php artisan vendor:publish --tag=relay-proxy-config
    

    Edit config/relay_proxy.php to define your API gateway routes, proxied endpoints, and middleware.

  2. First Use Case: Proxying a Simple API Define a route in config/relay_proxy.php:

    'routes' => [
        'api/v1/users' => [
            'target' => 'https://external-api.example.com/users',
            'methods' => ['GET', 'POST'],
            'middleware' => ['auth.api', 'throttle:60'],
        ],
    ],
    

    Now, requests to /api/v1/users will be proxied to the external API with the specified middleware applied.


Implementation Patterns

Core Workflow: Proxying with Middleware

  1. Route Definition Use the config/relay_proxy.php to map Laravel routes to external endpoints:

    'routes' => [
        'graphql' => [
            'target' => 'https://graphql.example.com',
            'methods' => ['POST'],
            'transform_request' => DigitalBlueprint\RelayProxyBundle\Transformer\RequestTransformer::class,
            'transform_response' => DigitalBlueprint\RelayProxyBundle\Transformer\ResponseTransformer::class,
        ],
    ],
    
  2. Middleware Integration Leverage Laravel’s middleware stack for pre/post-processing:

    'middleware' => [
        'auth:api',
        'throttle:100,1', // 100 requests per minute
        DigitalBlueprint\RelayProxyBundle\Http\Middleware\LogProxyRequest::class,
    ],
    
  3. Request/Response Transformation Extend the bundle’s transformer classes to modify payloads:

    namespace App\Transformers;
    
    use DigitalBlueprint\RelayProxyBundle\Transformer\AbstractTransformer;
    
    class CustomRequestTransformer extends AbstractTransformer {
        public function transform($request) {
            $request->merge(['api_key' => config('services.external_api.key')]);
            return $request;
        }
    }
    

    Register in config/relay_proxy.php:

    'transform_request' => App\Transformers\CustomRequestTransformer::class,
    
  4. Dynamic Routing Use route parameters to dynamically construct proxy targets:

    'routes' => [
        'api/v1/products/{id}' => [
            'target' => 'https://external-api.example.com/products/{id}',
            'methods' => ['GET'],
        ],
    ],
    

Advanced Patterns

  • Caching Responses Cache proxied responses using Laravel’s cache system:

    'cache' => [
        'enabled' => true,
        'ttl' => 300, // 5 minutes
        'prefix' => 'relay_proxy_',
    ],
    
  • Rate Limiting Combine with Laravel’s throttle middleware to limit external API calls:

    'middleware' => ['throttle:external_api,5'], // 5 requests per minute
    
  • Webhook Handling Proxy webhook requests to internal services:

    'webhooks' => [
        'stripe' => [
            'target' => 'https://internal-service.example.com/webhooks/stripe',
            'secret' => config('services.stripe.webhook_secret'),
            'verify_signature' => true,
        ],
    ],
    

Gotchas and Tips

Common Pitfalls

  1. CORS Issues If the proxied API enforces CORS, ensure your Laravel app includes the correct headers:

    'headers' => [
        'Access-Control-Allow-Origin' => '*',
        'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE',
    ],
    
  2. Middleware Order Middleware defined in config/relay_proxy.php runs after Laravel’s global middleware but before route-specific middleware. Adjust order if needed:

    // In RouteServiceProvider
    public function boot() {
        $this->app['router']->pushMiddlewareToGroup('web', \App\Http\Middleware\CustomProxyMiddleware::class);
    }
    
  3. SSL/TLS Verification Disable SSL verification only if absolutely necessary (e.g., for internal APIs):

    'client_options' => [
        'verify' => false, // Not recommended for production
    ],
    
  4. Route Conflict Avoid naming conflicts with existing Laravel routes. Prefix proxied routes (e.g., /proxy/api/v1/...).

  5. Large Payloads For large requests/responses, increase PHP’s limits in php.ini:

    post_max_size = 256M
    max_execution_time = 300
    

Debugging Tips

  • Log Proxy Requests Enable logging in config/relay_proxy.php:

    'debug' => [
        'log_requests' => true,
        'log_responses' => true,
    ],
    

    Check logs in storage/logs/laravel.log.

  • Test Locally Use curl to test proxy behavior:

    curl -X GET http://your-app.test/api/v1/proxied-endpoint -v
    
  • Inspect HTTP Clients The bundle uses Symfony’s HttpClient. Customize it in config:

    'client_options' => [
        'headers' => ['User-Agent' => 'Laravel-Relay-Proxy/1.0'],
        'timeout' => 30,
    ],
    

Extension Points

  1. Custom HTTP Clients Override the default client by binding your own:

    // In a service provider
    $this->app->bind(\Symfony\Contracts\HttpClient\HttpClientInterface::class, function () {
        return \Symfony\Contracts\HttpClient\HttpClient::create([
            'base_uri' => 'https://custom-base.example.com',
        ]);
    });
    
  2. Event Listeners Listen to proxy events (e.g., ProxyRequestSent, ProxyResponseReceived):

    // In EventServiceProvider
    protected $listen = [
        \DigitalBlueprint\RelayProxyBundle\Events\ProxyRequestSent::class => [
           \App\Listeners\LogProxyRequest::class,
       ],
    ];
    
  3. Dynamic Configuration Load proxy routes dynamically (e.g., from a database):

    // In a service provider
    $this->app->afterResolving(\DigitalBlueprint\RelayProxyBundle\RelayProxyBundle::class, function ($bundle) {
        $bundle->addRoute('dynamic/{id}', [
            'target' => 'https://api.example.com/dynamic/' . request('id'),
        ]);
    });
    
  4. Health Checks Add a health check endpoint for the proxy:

    'health_check' => [
        'enabled' => true,
        'route' => '/proxy/health',
        'target' => 'https://external-api.example.com/health',
    ],
    

    Accessible at /proxy/health to verify proxy connectivity.


---
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