How Microsoft Clarity Works
Clarity is a behavioral analytics tool that captures session recordings and generates heatmaps. It records user interactions by observing DOM mutations, mouse movements, clicks, scrolls, and page navigations. The recording engine uses a MutationObserver-based approach to serialize page state changes into a compressed event stream sent to Clarity servers.
The data model centers on three constructs:
- Sessions -- A sequence of page views from a single visitor within a 30-minute inactivity window. Sessions contain a recording timeline and associated metrics.
- Pages -- Individual pageviews within a session. Each page has its own heatmap data (click coordinates, scroll depth).
- Insights -- Automatically detected behavioral signals: dead clicks, rage clicks, quick-backs, excessive scrolling, and JavaScript errors.
Clarity processes recordings server-side to generate:
- Click heatmaps (aggregate click coordinates per page)
- Scroll heatmaps (percentage of users reaching each depth)
- Session playback (reconstructed DOM with mouse cursor overlay)
- Frustration scoring (sessions ranked by detected frustration signals)
Clarity is free with no traffic limits. Microsoft does not sell collected data. Sensitive form inputs (passwords, credit cards) are masked by default.
Installing the Tracking Script
Standard Installation
Add the Clarity tag to your site's <head>:
<script type="text/javascript">
(function(c,l,a,r,i,t,y){
c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
})(window, document, "clarity", "script", "YOUR_PROJECT_ID");
</script>
Replace YOUR_PROJECT_ID with the ID from your Clarity project settings (a short alphanumeric string like abc1def2gh).
Google Tag Manager
- Create a new Custom HTML tag in GTM.
- Paste the Clarity snippet above.
- Set the trigger to All Pages.
- Publish the container.
npm / Bundled Installation
npm install clarity-js
import { clarity } from 'clarity-js';
clarity.start({
projectId: 'YOUR_PROJECT_ID',
upload: 'https://www.clarity.ms/collect',
track: true,
content: true
});
Verify Installation
Open DevTools > Network and filter for clarity.ms. You should see requests to https://www.clarity.ms/collect with 200 responses. The Clarity dashboard will show data within 2 hours of the first recorded session.
Event Tracking and Data Collection
Custom Tags
Clarity does not have a general-purpose custom event system like PostHog or Mixpanel. Instead, it provides a custom tag API to attach key-value metadata to sessions:
// Set a custom tag (key-value pair attached to the session)
clarity("set", "user_type", "premium");
clarity("set", "ab_test", "variant_b");
clarity("set", "page_category", "checkout");
Custom tags appear as filterable dimensions in the Clarity dashboard. Use them to segment recordings and heatmaps by business-relevant attributes.
Built-In Behavioral Detection
Clarity automatically detects and labels these signals without any custom code:
| Signal | Detection Logic |
|---|---|
| Dead click | Click on a non-interactive element that produces no DOM change within 500ms |
| Rage click | 3+ clicks on the same element within a short window |
| Quick-back | User navigates to a page and returns within a few seconds |
| Excessive scrolling | Rapid up-and-down scrolling indicating confusion |
| JavaScript error | Uncaught exceptions captured via window.onerror and unhandledrejection |
| Resize | Browser window resize events |
Consent Mode
Respect user consent preferences:
// Start Clarity only after consent
if (userHasConsented()) {
clarity("consent");
}
// Or initialize with consent mode requiring explicit opt-in
clarity("start", {
projectId: "YOUR_PROJECT_ID",
consent: false // recording paused until clarity("consent") is called
});
Content Masking
Clarity masks sensitive content by default. Control masking granularity:
<!-- Mask all text inside this element -->
<div data-clarity-mask="true">
Sensitive content here
</div>
<!-- Unmask a specific section (when parent is masked) -->
<div data-clarity-unmask="true">
Public content
</div>
Mask entire regions programmatically:
clarity("set", "mask", ".user-profile, .account-details");
Identity and User Tracking
Custom User ID
Attach a user identifier to the Clarity session for cross-session analysis:
// Set a custom user ID (e.g., after login)
clarity("identify", "user-db-id-123", "session-token-abc", "page-id-xyz");
Parameters:
customUserId(required) -- Your internal user identifiercustomSessionId(optional) -- Your session identifiercustomPageId(optional) -- Your page identifier
After calling identify, the Clarity dashboard allows filtering by custom user ID to find all sessions from a specific user.
Session Identity
Clarity generates its own session and user identifiers stored in cookies:
_clck-- User ID cookie (expires in 1 year)_clsk-- Session ID cookie (expires after 30 minutes of inactivity)
These cookies enable returning visitor detection and session stitching across page navigations.
API and Data Export
Clarity API
Clarity provides a REST API for programmatic access to project data:
# Get project metadata
curl -X GET 'https://www.clarity.ms/api/v1/projects/YOUR_PROJECT_ID' \
-H 'Authorization: Bearer YOUR_API_TOKEN'
# Export session data
curl -X GET 'https://www.clarity.ms/api/v1/projects/YOUR_PROJECT_ID/sessions?start=2025-01-01&end=2025-01-31' \
-H 'Authorization: Bearer YOUR_API_TOKEN'
API tokens are generated in the Clarity project settings under Settings > API.
Google Analytics 4 Integration
Connect Clarity to GA4 to view session recordings directly in GA4 reports:
- In Clarity, go to Settings > Setup > Google Analytics integration.
- Authorize with your Google account.
- Select the GA4 property to link.
After linking:
- Clarity adds a
claritydimensioncustom dimension to GA4 containing the Clarity session URL. - You can view Clarity recordings from within GA4 by navigating to the custom dimension.
- Clarity sessions can be filtered by GA4 dimensions (traffic source, campaign, user properties).
Data Export via Dashboard
Clarity provides CSV export from the dashboard for:
- Session lists with metadata (duration, pages viewed, frustration score)
- Heatmap click coordinate data
- Aggregated metrics by page, device, or custom tag
Common Issues
Clarity Tag Not Recording
Verify the tag loads by checking DevTools > Network for clarity.ms requests. Common causes:
- Content Security Policy blocking: Add
https://www.clarity.mstoscript-srcandconnect-srcdirectives. - Ad blocker interference: Clarity is blocked by some ad blockers (uBlock Origin, Brave shields). This affects a subset of visitors; no workaround exists for those users.
- Duplicate tag installation: Multiple Clarity snippets on the same page cause conflicts. Ensure only one instance loads.
Heatmap Shows No Data
Heatmaps require a minimum number of sessions on a page before rendering. Newly added pages may take 24-48 hours to accumulate enough data. Also verify the page URL in the heatmap filter matches exactly (including trailing slashes and query parameters).
Session Recordings Are Blank
Blank recordings usually indicate a masking misconfiguration. If data-clarity-mask="true" is set on the <body> or a top-level container, the entire page appears masked in playback. Check for overly broad masking selectors.
High JavaScript Error Count
Clarity captures all uncaught exceptions via window.onerror. If your site has noisy third-party scripts throwing errors, Clarity will report them. These are real errors in the browser, not Clarity bugs. Filter by error message in the dashboard to separate first-party from third-party issues.
Cookie Consent Compliance
In regions requiring cookie consent (EU/GDPR), Clarity cookies (_clck, _clsk) require user consent before being set. Initialize Clarity in consent mode and call clarity("consent") only after the user opts in. Failure to do this can result in compliance violations.
Platform-Specific Considerations
Zero-Cost Model
Clarity is free with no session limits, no pageview caps, and no paid tiers. Microsoft funds Clarity as part of its broader web ecosystem strategy. There are no premium features behind a paywall. This makes Clarity viable for high-traffic sites where tools like Hotjar or FullStory would cost thousands per month.
Recording Sampling
Clarity may sample recordings on extremely high-traffic sites (millions of daily sessions). Sampling is automatic and not user-configurable. For most sites under 1M daily sessions, all sessions are recorded.
Single-Page Application Support
Clarity tracks SPA navigation by listening for pushState and replaceState changes. For frameworks that use hash-based routing, Clarity detects hashchange events. No additional configuration is needed for React, Vue, Angular, or Next.js apps.
Copilot AI Summaries
Clarity includes an AI-powered "Copilot" feature that generates natural-language summaries of session recordings and heatmap patterns. These summaries appear in the dashboard and describe what users did, where they struggled, and suggested areas for investigation. This feature uses Microsoft's AI models and processes data server-side.
Data Retention
Session recording data is retained for 30 days. Aggregated heatmap and insight data is retained longer. There is no option to extend retention since there is no paid tier.