Track the Usage of your Laravel APIs with the Measurement Protocol

• 5 min read

One lesser known feature of Google Analytics is the Measurement Protocol. Their docs describes the feature the best:

The Google Analytics Measurement Protocol allows developers to make HTTP requests to send raw user interaction data directly to Google Analytics servers. This allows developers to measure how users interact with their business from almost any environment.

When I first heard of this feature I couldn't see any useful appliance in my projects, but later last year I had the perfect use case: For a new API app my team and I developed we had to track how often each endpoint is used. In a normal app, where you have views with HTML and JavaScript you can use the Google Analytics JavaScript file analytics.js, but if you only return JSON that's not an option. But with a simple Middleware you can add a "backend tracking" to your Laravel app.

First, you have to have a Google Analytics property. If you don't have one, you should follow Google's guide here. Copy your Tracking ID / Property ID, we will need this very soon.

Next we install irazasyed/laravel-gamp, a Laravel package which abstract the rather complicated Measurement Protocol API away and gives us a nice PHP object to work with.

# Install the package
composer require irazasyed/laravel-gamp

# Publish the configuration
php artisan vendor:publish --provider="Irazasyed\LaravelGAMP\LaravelGAMPServiceProvider"

You can now set the tracking_id in config/gamp.php with the value from your Google Analytics property. While you're at it, I suggest updating the is_ssl, anonymize_ip and async_requests config to true.

The easiest way to apply a bit of code to all routes is by adding a new Middleware to Laravel. Let's create one through the artisan command:

php artisan make:middleware TrackThroughMeasurementProtocol

Open TrackThroughMeasurementProtocol.php and update the handle method like shown below:

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Str;
use Irazasyed\LaravelGAMP\Facades\GAMP;

class TrackThroughMeasurementProtocol
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Create a new UUID which is used as the Client ID
        $uuid = (string) Str::uuid();

        $gamp = GAMP::setClientId($uuid);
        $gamp->setDocumentPath('/' . $request->path());
        $gamp->setDocumentReferrer($request->server('HTTP_REFERER', ''));
        $gamp->setUserAgentOverride($request->server('HTTP_USER_AGENT'));

        // Override the sent IP with the IP from the current request.
        // Otherwhise the servers IP would be sent.
        $gamp->setIpOverride($request->ip());

        $gamp->sendPageview();

        return $next($request);
    }
}

First we create a new UUID which will be passed as the Client ID to the Measurement Protocol (You can read more about Client and User ID in the Google Analytics Docs). Next we set the document path, referrer and User Agent with the data the $request object gives us. This is important so Google Analytics actually knows on which paths your hits have occurred.

We also override the IP with the IP from the $request object. If you don't do this, Google Analytics will associate all hits with your servers IP. For example, if your server is located in the DigitalOcean NYC1 region and you look into your Google Analytics dashboard, all your visitors would be from New York, instead from all over the world. However, if the location of the requests is not important to you and you don't want to share the IP of your API consumers with Google, you can remove the setIpOverride part.

Register the Middleware in the Kernel #

In order to use our new Middleware we have to register it in app/Http/Kernel.php. If you want to apply it to all routes, add the class to the $middleware-property, if you only want to apply it to a certain group, add it to the $middlewareGroups-property and if you want to explicitly add it to just a handful routes, add it to the $routeMiddleware-property. I like to be explicit, so I will update my kernel like this.

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'track.measurementProtocol' => \App\Http\Middleware\TrackThroughMeasurementProtocol::class
    ];

Now you can just apply the Middleware to selected routes like this:

// routes/api.php
Route::middleware('track.measurementProtocol')->get('important-endpoint', function() {
    return ['important-data'];
});

All requests will now be tracked in your Google Analytics property, where you can start analysing how often your API endpoints are being called.

That's the very basic way how you can use the Measurement Protocol in your Laravel apps. If you read the docs, you will see that you can also do Event Tracking through the Measurement Protocol. In a real world example, Google shows how you can use this for email tracking (like to see, if your transaction emails are opened or event to A/B test emails).

If you found this article interesting and you would like to read more about how you could leverage GAMP in your projects, feel free to reach out through email. With enough feedback I might write another similar article.