Easy integration of Microsoft Clarity into your Laravel application.
You can install the package via composer:
composer require abr4xas/clarity-laravelYou can publish the config file with:
php artisan vendor:publish --tag="clarity-config"This is the contents of the published config file:
<?php
return [
'id' => env('CLARITY_ID', 'XXXXXX'),
'enabled' => env('CLARITY_ENABLED', true),
'enabled_identify_api' => env('CLARITY_IDENTIFICATION_ENABLED', false),
'global_tags' => [],
'consent_version' => env('CLARITY_CONSENT_VERSION', 'v2'),
'consent_required' => env('CLARITY_CONSENT_REQUIRED', false),
'auto_tag_environment' => env('CLARITY_AUTO_TAG_ENV', true),
'auto_tag_routes' => env('CLARITY_AUTO_TAG_ROUTES', false),
'auto_identify_users' => env('CLARITY_AUTO_IDENTIFY', false),
];Optionally, you can publish the views using
php artisan vendor:publish --tag="clarity-views"- Create an account: The first thing you need to do is create an account on Microsoft Clarity. You can sign up on their website and follow the steps to create your account. Then, get your tracking code and that's it.
- Simply add the blade components to your base layout files.
The enabled attribute is optional, but can be used to control the tags integration from blade files that extend the base layout. It accepts true/false.
This can still be controlled globally via the .env file should you need to disable the integration global on different environments as well.
<!-- Should be placed in the head -->
<x-clarity::script :enabled="$enabled" />Microsoft Clarity's Custom Tags API allows you to segment and filter sessions on the Clarity dashboard using custom metadata. This is useful for tracking user roles, subscription plans, feature flags, A/B test variants, and more.
<!-- Set a single value -->
<x-clarity::tag key="plan" :values="['premium']" />
<!-- Set multiple values -->
<x-clarity::tag key="features" :values="['chat', 'video', 'notifications']" />
<!-- Dynamic values -->
<x-clarity::tag key="user_role" :values="[auth()->user()->role]" />For more programmatic use cases, you can use the clarity_tag() helper function anywhere in your application:
// In a controller
clarity_tag('subscription', 'pro');
// Multiple values
clarity_tag('permissions', 'read', 'write', 'admin');
// Array of values
clarity_tag('features', ['feature_a', 'feature_b']);
// In middleware
class TrackUserSegment
{
public function handle($request, Closure $next)
{
if (auth()->check()) {
clarity_tag('user_segment', auth()->user()->segment);
}
return $next($request);
}
}The helper will return the rendered script tag which you can echo in your views, or it will return null if Clarity is disabled.
Global tags are automatically applied to all Clarity sessions. Define them in your config/clarity.php file:
'global_tags' => [
'environment' => [env('APP_ENV', 'production')],
'version' => ['1.0.0'],
'region' => ['us-east'],
],These tags will be automatically included when the Clarity script loads, making it easy to filter sessions by environment, version, or any other global attribute.
Microsoft Clarity supports Cookie Consent APIs for GDPR/CCPA compliance. This package supports both Consent V1 and V2.
// In config/clarity.php or .env
'consent_version' => env('CLARITY_CONSENT_VERSION', 'v2'), // 'v1' or 'v2'
'consent_required' => env('CLARITY_CONSENT_REQUIRED', false),<!-- Grant consent (V2 - recommended) -->
<x-clarity::consent :granted="true" />
<!-- Deny consent (V2) -->
<x-clarity::consent :granted="false" />// Grant consent
clarity_consent(true);
// Deny consent
clarity_consent(false);Important
Consent V2 is recommended and will be enforced for EEA, UK, and Switzerland users starting October 31, 2025.
The package includes middleware that automatically tags sessions with useful information:
- Environment tagging: Automatically tags sessions with the current environment (local, staging, production)
- Route tagging: Optionally tags sessions with route names and prefixes
- Auto-identification: Automatically identifies authenticated users
For Laravel 11+:
You need to manually register the middleware in your bootstrap/app.php file. Add it to the web middleware group:
// bootstrap/app.php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withMiddleware(function (Middleware $middleware) {
$middleware->web(append: [
\Abr4xas\ClarityLaravel\Middleware\ClarityMiddleware::class,
// or use the alias:
// 'clarity',
]);
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();For Laravel 10 and below:
You need to manually register the middleware in your app/Http/Kernel.php file. Add it to the web middleware group:
// app/Http/Kernel.php
protected $middlewareGroups = [
'web' => [
// ... other middleware
\Abr4xas\ClarityLaravel\Middleware\ClarityMiddleware::class,
// or use the alias:
// 'clarity',
],
];Alternatively, you can apply it to specific routes or route groups:
// In your routes file
Route::middleware('clarity')->group(function () {
// Your routes
});Configure the middleware behavior in config/clarity.php:
'auto_tag_environment' => env('CLARITY_AUTO_TAG_ENV', true),
'auto_tag_routes' => env('CLARITY_AUTO_TAG_ROUTES', false),
'auto_identify_users' => env('CLARITY_AUTO_IDENTIFY', false),When enabled, these tags and identifications are automatically included in your Clarity sessions without any additional code.
To implement the Identify API, use identify component.
Set CLARITY_IDENTIFICATION_ENABLED value to true on the env file.
userattribute is required accepts the User Model instance or any object. Theemailandnameattributes are used.enabledattribute is optional.custom_session_idattribute is optional.custom_page_idattribute is optional.
@auth
<x-clarity::identify :user="request()->user()"/>
@endauthThis will compile as:
window.clarity("identify", "[email protected]", null, null, "Username")You can also use the clarity_identify() helper for programmatic identification:
// Basic usage
clarity_identify(auth()->user());
// With custom session and page IDs
clarity_identify(
user: auth()->user(),
customSessionId: 'custom-session-123',
customPageId: 'checkout-page'
);You can set custom user IDs, session IDs, and page IDs independently using dedicated helpers or components. Note: These require the Identify API to be enabled (CLARITY_IDENTIFICATION_ENABLED=true).
// Set custom user ID
clarity_set_custom_user_id('user-123');
// Set custom session ID
clarity_set_custom_session_id('session-456');
// Set custom page ID
clarity_set_custom_page_id('page-789');<x-clarity::custom-user-id user_id="user-123" />
<x-clarity::custom-session-id session_id="session-456" />
<x-clarity::custom-page-id page_id="page-789" />The package includes a queue system that ensures tags and other Clarity API calls are executed even if Clarity hasn't fully loaded yet. This is handled automatically - tags are queued and processed when Clarity becomes available.
You can also manually include the queue component if needed:
<x-clarity::queue />This package provides convenient helper functions for use anywhere in your Laravel application:
clarity_tag(string $key, mixed ...$values): ?string- Set custom tags for session filteringclarity_identify(object $user, ?string $customSessionId = null, ?string $customPageId = null): ?string- Identify a user in the current session (requires Identify API enabled)clarity_consent(bool $granted = true): ?string- Set consent for the current sessionclarity_set_custom_user_id(string $userId): ?string- Set a custom user ID (requires Identify API enabled)clarity_set_custom_session_id(string $sessionId): ?string- Set a custom session ID (requires Identify API enabled)clarity_set_custom_page_id(string $pageId): ?string- Set a custom page ID (requires Identify API enabled)
These helpers respect your configuration settings and will return null when Clarity is disabled.
// config/clarity.php
return [
'id' => env('CLARITY_ID'),
'enabled' => env('CLARITY_ENABLED', true),
'enabled_identify_api' => true,
'auto_tag_environment' => true,
'auto_tag_routes' => true,
'auto_identify_users' => true,
'global_tags' => [
'app_version' => [config('app.version')],
'deployment' => [env('DEPLOYMENT_ID')],
],
];// In your cookie consent handler
if ($userConsented) {
echo clarity_consent(true);
} else {
echo clarity_consent(false);
}// In a controller after user action
public function upgradePlan(Request $request)
{
// ... upgrade logic ...
// Tag the session for analysis
clarity_tag('plan_upgrade', [
'from' => $request->user()->plan,
'to' => $request->input('new_plan'),
'timestamp' => now()->toIso8601String(),
]);
return redirect()->route('dashboard');
}composer testPlease see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.
This package is strongly inspired by Google Tag Manager for Laravel created by @awcodes.