Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Global HTTP middleware in Laravel 10.x

Sometimes when working with third-party APIs, there might be a need to add common headers to all the outgoing requests. For instance, you might want to add an Authorization header to all the outgoing requests to authenticate the requests.

The other and most practical use case would be to add a User-Agent header in all the outgoing requests to the third-party APIs. This is because some APIs require you to add a User-Agent header in the request to identify the client.

This PR in Laravel 10.x introduces an ability to alter all the outgoing requests and incoming responses by using global HTTP middleware.

The global request middleware

So, if we want to add a User-Agent header to all the outgoing requests, we can do so by creating a new global request middleware in the boot method of the app’s AppServiceProvider like so.

use Illuminate\Support\Facades\Http;

Http::globalRequestMiddleware(
    fn ($request) => $request->withHeader(
        'User-Agent', 
        'MyApp/1.0 (https://example.com) | [email protected]'
    )
);

This will add the User-Agent header to all the outgoing requests.

The global response middleware

Similarly, if you want to add a global response middleware, you can do so by using the globalResponseMiddleware method like so.

use Illuminate\Support\Facades\Http;

Http::globalResponseMiddleware(
    fn ($response) => $response->withHeader(
        'X-Response-Time', 
        $response->serverTiming()->totalDuration()
    )
);

The global request and response cycle middleware

You can also register a global middleware that handles the entire request and response cycle by using the globalMiddleware method like so.

use Illuminate\Support\Facades\Http;

Http::globalMiddleware(function ($handler) {
    return function ($request, $options) use ($handler) {
        $startedAt = now();

        return $handler($request, $options)
            ->then(fn ($response) => $response->withHeader(
                'X-Duration', $startedAt->diffInMilliseconds(now())
            ));
    };
});

As you can tell, the above middleware will add an X-Duration header to the response which will contain the duration of the request in milliseconds.

Closing thoughts

I think this is a great addition to the framework as it will allow you to alter all the outgoing requests and incoming responses in a single place. This will also help you to keep your code DRY and clean.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?