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

Guzzle Redirect History Middleware Laravel Package

spatie/guzzle-redirect-history-middleware

Guzzle middleware that records redirect chains for each request. Attach RedirectHistoryMiddleware to your handler stack to capture every Location hop and inspect the final URL and intermediate redirects via a RedirectHistory instance.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Lightweight & Focused: The package is a minimal middleware for Guzzle, making it a low-overhead solution for tracking HTTP redirects. It aligns well with Laravel’s HTTP client layer (Guzzle-based) and does not introduce architectural complexity.
  • Stateless & Decoupled: Since it operates purely as middleware, it does not require application-level state management, reducing coupling with business logic.
  • Observability-First: Ideal for debugging, logging, or analytics use cases where redirect chains need visibility (e.g., API integrations, web scraping, or compliance tracking).

Integration Feasibility

  • Guzzle Compatibility: Works seamlessly with Laravel’s built-in HTTP client (Http::client()) or custom Guzzle stacks. No breaking changes expected given Guzzle’s stable API.
  • Laravel Ecosystem Fit: Integrates cleanly with Laravel’s service container and middleware stack. Can be injected into:
    • Global HTTP client middleware (via Http::macro('withMiddleware', ...)).
    • Per-request middleware (via Http::withMiddleware()).
    • Custom Guzzle clients (e.g., in service classes).
  • Data Access: Redirect history is exposed via a simple array, enabling easy serialization (e.g., for logging or metrics).

Technical Risk

  • Low Risk: MIT-licensed, battle-tested (19 stars, CI/CD in place), and minimal surface area for bugs.
  • Deprecation Risk: Last release in 2021 raises concerns about:
    • Compatibility with Guzzle 7+ (released 2022). Test for GuzzleHttp\Psr7\Request/Response changes.
    • Lack of recent maintenance (though core functionality is unlikely to break).
  • Performance Impact: Redirect tracking adds minimal overhead (only stores history in memory). No known scalability bottlenecks.

Key Questions

  1. Guzzle Version Support:
    • Is the app using Guzzle 6 or 7? If 7, verify middleware works with PSR-7 interfaces.
    • Can we fork/maintain if upstream stalls? (MIT license allows this.)
  2. Use Case Clarity:
    • Is this for debugging, analytics, or compliance? (Affects logging strategy.)
    • Do redirects need to be persisted (e.g., in a database) or just observed?
  3. Alternatives:
    • Could Laravel’s built-in Http::history() (if using Http::macro) suffice?
    • For advanced use cases, consider monolog/handler for structured logging.
  4. Testing:
    • How will we verify redirect tracking in CI? (Mock Guzzle or use Http::fake().)

Integration Approach

Stack Fit

  • Laravel HTTP Client: Native integration via Http::withMiddleware() or global middleware.
    // Global middleware (app/Providers/AppServiceProvider.php)
    public function boot(): void
    {
        Http::macro('withRedirectHistory', function () {
            return Http::withMiddleware(function (callable $handler) {
                return function (RequestInterface $request, array $options) use ($handler) {
                    $middleware = new \Spatie\GuzzleRedirectHistoryMiddleware\RedirectHistoryMiddleware();
                    return $middleware->process($request, $options, $handler);
                };
            });
        });
    }
    
  • Custom Guzzle Clients: Inject middleware into standalone Guzzle clients (e.g., in services).
    $client = new Client([
        'middleware' => [
            new \Spatie\GuzzleRedirectHistoryMiddleware\RedirectHistoryMiddleware(),
        ],
    ]);
    
  • Service Container: Bind the middleware to Laravel’s container for dependency injection.

Migration Path

  1. Phase 1: Proof of Concept
    • Add middleware to a non-critical HTTP client (e.g., a background job).
    • Verify redirect history is captured as expected.
    • Test with Guzzle 7 if applicable.
  2. Phase 2: Gradual Rollout
    • Roll out to API integrations or scraping services first.
    • Monitor for performance regressions (unlikely, but log response times).
  3. Phase 3: Global Adoption
    • Apply as global middleware if needed (e.g., for compliance).
    • Document usage in API clients/services.

Compatibility

  • Laravel Versions: Compatible with Laravel 7+ (Guzzle 6/7 support).
  • Guzzle Versions:
    • Guzzle 6: Tested (package origin).
    • Guzzle 7: Requires validation (PSR-7 compliance).
  • PHP Versions: No issues with PHP 8.0+ (package supports 7.4+).

Sequencing

  1. Dependency Update: Ensure Guzzle is up-to-date (preferably 7.x).
  2. Middleware Injection: Start with localized usage (e.g., specific services).
  3. Logging/Observability: Integrate with Laravel Log or a dedicated service (e.g., Sentry).
  4. Documentation: Update API client docs to note redirect tracking behavior.

Operational Impact

Maintenance

  • Low Effort: Minimal maintenance required (no moving parts beyond middleware).
  • Forking Strategy: If upstream stalls, fork and maintain (MIT license permits this).
  • Dependency Updates: Monitor Guzzle major versions for breaking changes.

Support

  • Debugging: Redirect history simplifies troubleshooting for:
    • 3xx responses (e.g., misconfigured APIs).
    • Circular redirects (infinite loops).
  • Analytics: Enable tracking of redirect patterns (e.g., A/B testing, performance).
  • Compliance: Audit redirect chains for GDPR/legal requirements (e.g., tracking consent).

Scaling

  • Memory Usage: Redirect history is in-memory only; no database or external storage by default.
    • For high-volume requests, consider truncating history after use.
  • Performance: Negligible impact on latency (only stores metadata).
  • Horizontal Scaling: No distributed state; works identically across all instances.

Failure Modes

Failure Scenario Impact Mitigation
Middleware throws exception HTTP request fails Wrap in try-catch or use Guzzle’s error handling.
Redirect loop (infinite) High CPU/memory usage Set max_redirects in Guzzle config.
Guzzle version incompatibility Middleware fails silently Test with target Guzzle version early.
Logging overload High disk I/O (if logging all) Filter redirects (e.g., only 3xx codes).

Ramp-Up

  • Developer Onboarding:
    • 5–10 minutes to integrate middleware into a client.
    • 15–30 minutes to set up logging/observability.
  • Documentation Needs:
    • Add examples for:
      • Accessing redirect history in responses.
      • Customizing middleware behavior (e.g., filtering).
      • Handling edge cases (e.g., malformed redirects).
  • Training:
    • Highlight use cases (debugging, analytics) in team docs.
    • Encourage use in new API integrations first.
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport