Documentation menuProxy setups: Laravel

Proxy setups

Proxy the Loogika script with Laravel

In Laravel you proxy Loogika with a small controller and a group of routes. The routes catch requests under a path such as /stats, and the controller forwards them to app.loogika.com with Laravel's HTTP client. You also exclude the routes from CSRF protection.

Last updated .

What do you need before you start?

You need Laravel 8 or later and your Loogika site ID. The site ID sits in the script tag under Site Settings in Loogika, on the Tracking Script tab.

The proxy guide explains why a proxy on your own domain helps against ad blockers. The page you are reading covers the Laravel code only.

What does the proxy controller look like?

The controller has one method for the script files, one for the tracking settings and one for every POST request. Create the file with Artisan and replace its content with the code below:

php artisan make:controller AnalyticsProxyController
<?php
// app/Http/Controllers/AnalyticsProxyController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class AnalyticsProxyController extends Controller
{
    private const LOOGIKA_HOST = 'https://app.loogika.com';

    // Headers that describe the hop to your app and not the visitor's browser,
    // plus credentials that must not leave your server.
    private const SKIP_HEADERS = [
        'host', 'content-length', 'connection', 'cookie', 'keep-alive',
        'transfer-encoding', 'upgrade', 'x-forwarded-for', 'x-forwarded-host',
        'x-forwarded-proto', 'x-forwarded-port', 'x-real-ip',
        'authorization', 'proxy-authorization',
    ];

    /**
     * Script files (GET), cached for 1 hour
     */
    public function proxyScript(Request $request, string $script)
    {
        return $this->cached("loogika_script_{$script}", 3600, "api/{$script}", $request);
    }

    /**
     * Tracking settings of the site (GET), cached for 5 minutes
     */
    public function proxySiteConfig(Request $request, string $siteId)
    {
        return $this->cached("loogika_config_{$siteId}", 300, "api/site/tracking-config/{$siteId}", $request);
    }

    /**
     * Every POST request the script sends
     */
    public function proxyPost(Request $request)
    {
        // Strip the leading "stats/" and forward to the same path under /api
        $path = 'api/' . substr($request->path(), strlen('stats/'));

        return $this->forward('POST', $path, $request);
    }

    private function cached(string $key, int $ttl, string $path, Request $request)
    {
        $cached = Cache::get($key);

        if ($cached === null) {
            $response = $this->forward('GET', $path, $request);

            if ($response->getStatusCode() !== 200) {
                return $response;
            }

            $cached = [
                'body' => $response->getContent(),
                'type' => $response->headers->get('Content-Type'),
            ];
            Cache::put($key, $cached, $ttl);
        }

        return response($cached['body'], 200)->header('Content-Type', $cached['type']);
    }

    private function forward(string $method, string $path, Request $request)
    {
        $url = self::LOOGIKA_HOST . "/{$path}";

        // Pass the browser's headers through. Bot detection expects them.
        $headers = collect($request->headers->all())
            ->reject(fn ($value, $name) => in_array(strtolower($name), self::SKIP_HEADERS, true))
            ->map(fn ($values) => implode(', ', $values))
            ->all();

        // The visitor IP. $request->ip() follows your TrustProxies settings.
        $headers['X-Forwarded-For'] = $request->ip();
        // Replace the copied Accept-Encoding with gzip, which the HTTP client
        // can decode. Send it only if the browser offered gzip.
        $headers['accept-encoding'] = str_contains($request->header('Accept-Encoding', ''), 'gzip') ? 'gzip' : 'identity';

        $http = Http::timeout(30)->withHeaders($headers);

        try {
            $response = $method === 'POST'
                // Forward the raw body and do not re-encode it
                ? $http->withBody($request->getContent(), $request->header('Content-Type', 'application/json'))->post($url)
                : $http->get($url);

            return response($response->body(), $response->status())
                ->header('Content-Type', $response->header('Content-Type') ?: 'text/plain');
        } catch (\Throwable $e) {
            Log::error('Loogika proxy error', ['url' => $url, 'error' => $e->getMessage()]);

            return response()->json(['error' => 'Analytics proxy error'], 502);
        }
    }
}

The controller copies the browser's headers because Loogika's bot detection looks at them. A proxy that sends only the user agent and the IP address looks like an automated client.

POST bodies go out exactly as they came in, through $request->getContent(). Do not rebuild the body from $request->all(). Laravel's ConvertEmptyStringsToNull middleware turns empty strings into null there, and the event data changes.

Which routes does Loogika need in routes/web.php?

Loogika needs six routes under the stats prefix. Together they cover every address the script calls:

<?php
// routes/web.php

use App\Http\Controllers\AnalyticsProxyController;

Route::prefix('stats')->group(function () {
    // Script files (GET). replay.js loads only when session replay is on.
    Route::get('/{script}', [AnalyticsProxyController::class, 'proxyScript'])
        ->where('script', '(script|replay)\.js');

    // Tracking settings (GET)
    Route::get('/site/tracking-config/{siteId}', [AnalyticsProxyController::class, 'proxySiteConfig']);

    // Requests the script sends (POST)
    Route::post('/track', [AnalyticsProxyController::class, 'proxyPost']);
    Route::post('/identify', [AnalyticsProxyController::class, 'proxyPost']);
    Route::post('/site/{siteId}/feature-flags/evaluate', [AnalyticsProxyController::class, 'proxyPost']);
    Route::post('/session-replay/record/{siteId}', [AnalyticsProxyController::class, 'proxyPost']);
});

Keep the file name script.js. The script works out where its events go by cutting its own address at /script.js. With another file name, every request ends up at a wrong address.

Why do the routes need a CSRF exception?

The Loogika script sends no CSRF token, and Laravel applies its CSRF check to every route in routes/web.php. Laravel answers its POST requests with status 419 until you exclude the paths.

In Laravel 11 and later you add the exception in bootstrap/app.php:

<?php
// bootstrap/app.php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    // ...
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->validateCsrfTokens(except: [
            'stats/*',
        ]);
    })
    // ...
    ->create();

In Laravel 10 and earlier the list sits in the VerifyCsrfToken middleware:

// app/Http/Middleware/VerifyCsrfToken.php
protected $except = [
    'stats/*',
];

How do you load the script through the proxy?

Point the script tag in your Blade layout at the proxied path:

{{-- resources/views/layouts/app.blade.php --}}
<script src="{{ url('/stats/script.js') }}?siteId=YOUR_SITE_ID" defer></script>

Then turn on First-Party Proxy under Site Settings, General in Loogika. The switch tells Loogika to trust the IP address your controller sends in X-Forwarded-For.

A load balancer or a CDN in front of your app means you must also configure Laravel's trusted proxies. Otherwise $request->ip() returns the address of the load balancer and not the visitor's.

How do you check that the Laravel proxy works?

Clear the route cache with php artisan route:clear if you cache routes. Then open your site with the browser's developer tools and look at the Network tab.

The script and the requests to /stats/track should go to your own domain and return status 200. Your visit should then appear in the realtime view in Loogika with your real location.

What goes wrong most often with a Laravel proxy?

SymptomFix
The routes return 404Run php artisan route:clear, then list the routes with php artisan route:list --path=stats
POST requests return 419Add stats/* to the CSRF exceptions
Every visitor has the location of your serverTurn on First-Party Proxy and configure trusted proxies, so $request->ip() is the visitor's address
/stats/track returns 200, but no visits appearCheck that the controller forwards all browser headers and the raw POST body
An old script stays in the cacheRun php artisan cache:forget loogika_script_script.js

Can you queue or rate-limit the proxied requests?

Do not queue them. Forward every request while the visitor's request is still open, and return Loogika's own response. A queued job runs outside the request and no longer has the browser's headers, so Loogika treats its events as bot traffic.

You can rate-limit the routes with Laravel's throttle middleware, for example throttle:100,1 for 100 requests per minute. Session replay sends a batch every few seconds while it records, so keep the limit well above that.