Inspecting Server-to-Server Requests in Laravel with Clockwork: A How-To Guide
Tags: laravel
Published: 2023-04-13 09:27:21

When building web applications, server-to-server communication is a common requirement. However, when something goes wrong with these requests, it can be challenging to debug the issue without proper insight into what is happening under the hood. Fortunately, Laravel provides an HTTP client that simplifies server-to-server communication, and Clockwork provides a powerful debugging tool that can help us inspect and debug these requests.

In this post, we'll walk through how to use Clockwork to inspect server-to-server requests in Laravel.

```php
use Illuminate\Support\Facades\Http;

$response = Http::get('https://jsonplaceholder.typicode.com/posts/1');
$body = $response->body();
```

### Setting Up Clockwork

Before we can start inspecting our server-to-server requests, we first need to set up Clockwork in our Laravel application. We can install Clockwork by running the following command in our terminal:

```
composer require --dev itsgoingd/clockwork
```

Next, we need to register the Clockwork middleware in our application's middleware stack. We can do this by adding the following line to our `app/Http/Kernel.php` file:

```php
protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \Illuminate\Foundation\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \Illuminate\Foundation\Http\Middleware\TrustProxies::class,

    // Add the following line to register the Clockwork middleware
    \Clockwork\Support\Laravel\ClockworkMiddleware::class,
];
```

With the Clockwork middleware registered, we can start using it to inspect our server-to-server requests.

### Inspecting Server-to-Server Requests

The provided code snippet demonstrates how we can use Clockwork to log the details of our server-to-server requests. We can add this code to a service provider in our application, such as `app/Providers/ServiceProvider.php`:

```php
<?php

declare(strict_types=1);

namespace App\Providers;

use Illuminate\Http\Client\Events\RequestSending;
use Illuminate\Http\Client\Events\ResponseReceived;
use Illuminate\Support\Facades\Event;

class ServiceProvider extends \Illuminate\Support\ServiceProvider
{
    public function boot()
    {
        Event::listen(function (RequestSending $event) {
            $headersText = collect($event->request->headers())
                ->map(fn($values, $key) => $key . ": " . (is_array($values) ? implode(", ", $values) : $values))
                ->join("\r\n");
            clock("{$event->request->method()} {$event->request->url()}\r\n{$headersText}\r\n\r\n{$event->request->body()}");
        });
        Event::listen(function (ResponseReceived $event) {
            $headersText = collect($event->response->headers())
                ->map(fn($values, $key) => $key . ": " . (is_array($values) ? implode(", ", $values) : $values))
                ->join("\r\n");
            $body = $event->response->body();
            clock("{$event->response->status()} {$event->request->method()} {$event->request->url()}\r\n{$headersText}\r\n\r\n{$body}");
        });
    }
}
```

In this code snippet, we're using Laravel's event system to listen for `RequestSending` and `ResponseReceived` events. When these events occur, we're using the `clock` function to log the details of the request or response.

We're formatting the logs in a standard HTTP request/response format that includes the request/response status, method, URL, headers, and body.

Here is an example on how this looks like in your local development: http://localhost/clockwork/app#

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3kw7f9667zqukwjeyf8r.png)