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
- The global response middleware
- The global request and response cycle middleware
- Closing thoughts
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.
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.