Hotjar Install / Embed Tag or SDK | OpsBlu Docs

Hotjar Install / Embed Tag or SDK

Deployment approaches for installing Hotjar tracking code across web, mobile, and server environments.

Installation Methods Overview

Hotjar offers several deployment options depending on your tech stack, team structure, and use case. Choose the method that best fits your workflow:

Method Best For Pros Cons
Direct Embed Simple sites, full dev control Fast, no dependencies Requires code deployment for changes
Google Tag Manager Most teams, frequent changes No code deploys, easy testing Slight overhead, requires GTM setup
Segment Multi-tool analytics stack Centralized tracking Added abstraction layer
WordPress Plugin WordPress sites No code required Limited customization
Shopify Integration E-commerce on Shopify Built for Shopify Shopify-specific
Custom API Advanced use cases Full control Requires development

Getting Your Tracking Code

  1. Log in to Hotjar
  2. Go to Sites & Organizations
  3. Select your site (or create a new one)
  4. Copy the tracking code from the Tracking Code section

Standard Installation

Paste the tracking code in the <head> section of every page you want to track:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Your Page Title</title>

    <!-- Hotjar Tracking Code for Site ID: YOUR_SITE_ID -->
    <script>
        (function(h,o,t,j,a,r){
            h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
            h._hjSettings={hjid:YOUR_SITE_ID,hjsv:6};
            a=o.getElementsByTagName('head')[0];
            r=o.createElement('script');r.async=1;
            r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
            a.appendChild(r);
        })(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
    </script>
    <!-- End Hotjar Tracking Code -->

</head>
<body>
    <!-- Your content -->
</body>
</html>

Important: Replace YOUR_SITE_ID with your actual Hotjar Site ID (found in your Hotjar dashboard)

Verification

After installation, verify Hotjar is working:

  1. Visit your website
  2. Open browser DevTools (F12)
  3. Go to Console tab
  4. Type: console.log(typeof hj)
  5. Should return: "function"

Or check the Hotjar dashboard:

  1. Go to Sites & Organizations
  2. Your site status should show "Installed" (may take a few minutes)

Environment-Specific Installation

Use server-side logic to inject different Site IDs per environment:

PHP Example:

<?php
$hotjar_id = ($_SERVER['SERVER_NAME'] === 'www.example.com')
    ? '123456'  // Production
    : '789012'; // Staging
?>

<script>
    (function(h,o,t,j,a,r){
        h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
        h._hjSettings={hjid:<?php echo $hotjar_id; ?>,hjsv:6};
        // ... rest of code
    })(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
</script>

Node.js/Express Example:

// In your template
const hotjarId = process.env.NODE_ENV === 'production'
    ? process.env.HOTJAR_ID_PROD
    : process.env.HOTJAR_ID_DEV;

// Pass to view
res.render('page', { hotjarId });
<!-- In your view template -->
<script>
    (function(h,o,t,j,a,r){
        h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
        h._hjSettings={hjid:<%= hotjarId %>,hjsv:6};
        // ... rest of code
    })(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
</script>

GTM is the preferred method for most teams because it allows marketing and analytics teams to manage tracking without developer involvement.

Prerequisites

  • Google Tag Manager container installed on your site
  • Admin access to GTM
  • Hotjar Site ID

Setup Instructions

Step 1: Create Hotjar Tag

  1. Log in to Google Tag Manager
  2. Go to Tags > New
  3. Click Tag Configuration
  4. Select Custom HTML
  5. Name the tag: Hotjar Tracking

Step 2: Add Tracking Code

Paste your Hotjar tracking code:

<script>
    (function(h,o,t,j,a,r){
        h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
        h._hjSettings={hjid:{{Hotjar Site ID}},hjsv:6};
        a=o.getElementsByTagName('head')[0];
        r=o.createElement('script');r.async=1;
        r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
        a.appendChild(r);
    })(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
</script>

Step 3: Create GTM Variable (Optional but Recommended)

For cleaner management:

  1. Go to Variables > New
  2. Name: Hotjar Site ID
  3. Type: Constant
  4. Value: Your Hotjar Site ID (e.g., 1234567)

Then update the tag to reference the variable:

h._hjSettings={hjid:{{Hotjar Site ID}},hjsv:6};

Step 4: Set Trigger

  1. Under Triggering, click to add a trigger
  2. Select All Pages (Page View trigger)
  3. Optionally, add exceptions for internal traffic or specific pages

Step 5: Test in Preview Mode

  1. Click Preview in GTM
  2. Enter your website URL
  3. Browse your site
  4. In GTM Debug panel, verify Hotjar Tracking tag fires on page load
  5. Check browser console: console.log(typeof hj) should return "function"

Step 6: Publish

  1. Click Submit in GTM
  2. Add version name and description
  3. Click Publish

Advanced GTM Configuration

Conditional Loading (Exclude Internal Traffic):

Create a trigger that excludes your office IP:

  1. Triggers > New
  2. Type: Page View
  3. Name: All Pages - External Only
  4. This trigger fires on: Some Page Views
  5. Condition: Page Hostname does not contain staging.yoursite.com
  6. Or: IP Address does not equal 203.0.113.0 (your office IP)

Multi-Environment Setup:

Use GTM Environments to manage different Site IDs:

  1. Create GTM Variable: Hotjar Site ID
  2. Default value: Production Site ID
  3. In GTM Environments, override variable for staging/dev

Or use Lookup Table:

  1. Variables > New > Lookup Table
  2. Input Variable: {{Page Hostname}}
  3. Map hostnames to Site IDs:
    • www.example.com1234567 (production)
    • staging.example.com7654321 (staging)

Segment Integration

Segment is a customer data platform that lets you collect data once and send it to multiple tools.

Setup

In Segment Dashboard:

  1. Go to Destinations > Add Destination
  2. Search for "Hotjar"
  3. Click Configure Hotjar
  4. Select source(s) to connect
  5. Enter your Hotjar Site ID
  6. Enable the destination

In Your Code:

No Hotjar-specific code needed. Segment handles everything:

// Page view (auto-tracked in most Segment libraries)
analytics.page('Homepage');

// Identify user
analytics.identify('user_123', {
  email: 'user@example.com',
  plan: 'premium',
  signup_date: '2024-01-15'
});

// Track custom event
analytics.track('Signup Button Clicked', {
  location: 'homepage',
  button_color: 'blue'
});

These automatically translate to Hotjar:

hj('stateChange', '/homepage');
hj('identify', 'user_123', {
  email: 'user@example.com',
  plan: 'premium',
  signup_date: '2024-01-15'
});
hj('event', 'Signup Button Clicked');

Note: Event properties are not passed to Hotjar (limitation of Hotjar's API). Use descriptive event names instead.

Benefits of Segment

  • Single tracking implementation for all tools
  • Easy to add/remove tools without code changes
  • Centralized data governance
  • Historical replay (backfill Hotjar when first connected)

Limitations

  • Event properties not forwarded to Hotjar
  • Additional cost for Segment service
  • Slight delay in data processing

WordPress Installation

Method 1: Plugin

  1. In WordPress admin, go to Plugins > Add New
  2. Search for "Insert Headers and Footers"
  3. Install and activate
  4. Go to Settings > Insert Headers and Footers
  5. Paste Hotjar code in Scripts in Header section
  6. Click Save

Method 2: Theme Functions

Add to your theme's functions.php:

function add_hotjar_tracking() {
    ?>
    <!-- Hotjar Tracking Code -->
    <script>
        (function(h,o,t,j,a,r){
            h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
            h._hjSettings={hjid:YOUR_SITE_ID,hjsv:6};
            a=o.getElementsByTagName('head')[0];
            r=o.createElement('script');r.async=1;
            r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
            a.appendChild(r);
        })(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
    </script>
    <?php
}
add_action('wp_head', 'add_hotjar_tracking');

Best Practice: Use a child theme to avoid losing changes during theme updates.

Shopify Installation

Setup

  1. In Shopify admin, go to Online Store > Themes
  2. Click Actions > Edit code
  3. Find and open theme.liquid
  4. Locate the </head> tag
  5. Paste Hotjar tracking code just before </head>
  6. Click Save
<!DOCTYPE html>
<html>
<head>
    <!-- Shopify theme head content -->

    <!-- Hotjar Tracking Code -->
    <script>
        (function(h,o,t,j,a,r){
            h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
            h._hjSettings={hjid:YOUR_SITE_ID,hjsv:6};
            a=o.getElementsByTagName('head')[0];
            r=o.createElement('script');r.async=1;
            r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
            a.appendChild(r);
        })(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
    </script>
    <!-- End Hotjar Tracking Code -->

</head>
<body>
    <!-- Shopify theme content -->
</body>
</html>

Tracking E-commerce Events

Add custom events for shopping behavior:

<script>
// Track add to cart
{% if template contains 'product' %}
    document.addEventListener('DOMContentLoaded', function() {
        var addToCartButton = document.querySelector('[name="add"]');
        if (addToCartButton) {
            addToCartButton.addEventListener('click', function() {
                hj('event', 'add_to_cart');
            });
        }
    });
{% endif %}

// Track checkout
{% if checkout %}
    hj('event', 'checkout_started');
{% endif %}

// Track purchase
{% if first_time_accessed %}
    hj('event', 'purchase_completed');
{% endif %}
</script>

Single Page Application (SPA) Installation

React

Install Hotjar in index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>React App</title>

    <!-- Hotjar Tracking Code -->
    <script>
        (function(h,o,t,j,a,r){
            h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
            h._hjSettings={hjid:YOUR_SITE_ID,hjsv:6};
            a=o.getElementsByTagName('head')[0];
            r=o.createElement('script');r.async=1;
            r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
            a.appendChild(r);
        })(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
    </script>
</head>
<body>
    <div id="root"></div>
</body>
</html>

Track Route Changes:

// In your App component or custom hook
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

function useHotjarPageTracking() {
    const location = useLocation();

    useEffect(() => {
        if (window.hj) {
            window.hj('stateChange', location.pathname);
        }
    }, [location]);
}

// Usage in App.js
function App() {
    useHotjarPageTracking();

    return (
        <div className="App">
            {/* Your routes */}
        </div>
    );
}

Vue.js

Install in public/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Vue App</title>

    <!-- Hotjar Tracking Code -->
    <script>
        (function(h,o,t,j,a,r){
            h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
            h._hjSettings={hjid:YOUR_SITE_ID,hjsv:6};
            a=o.getElementsByTagName('head')[0];
            r=o.createElement('script');r.async=1;
            r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
            a.appendChild(r);
        })(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
    </script>
</head>
<body>
    <div id="app"></div>
</body>
</html>

Track Route Changes:

// In your router (router/index.js)
import { createRouter, createWebHistory } from 'vue-router';

const router = createRouter({
    history: createWebHistory(),
    routes: [
        // your routes
    ]
});

router.afterEach((to) => {
    if (window.hj) {
        window.hj('stateChange', to.path);
    }
});

export default router;

Angular

Install in src/index.html:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Angular App</title>

    <!-- Hotjar Tracking Code -->
    <script>
        (function(h,o,t,j,a,r){
            h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
            h._hjSettings={hjid:YOUR_SITE_ID,hjsv:6};
            a=o.getElementsByTagName('head')[0];
            r=o.createElement('script');r.async=1;
            r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
            a.appendChild(r);
        })(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
    </script>
</head>
<body>
    <app-root></app-root>
</body>
</html>

Track Route Changes:

// In app.component.ts
import { Component } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})
export class AppComponent {
    constructor(private router: Router) {
        this.router.events.pipe(
            filter(event => event instanceof NavigationEnd)
        ).subscribe((event: NavigationEnd) => {
            if (window['hj']) {
                window['hj']('stateChange', event.urlAfterRedirects);
            }
        });
    }
}

Content Security Policy (CSP) Configuration

If your site uses CSP headers, you must whitelist Hotjar domains:

Content-Security-Policy:
    script-src 'self' https://static.hotjar.com https://script.hotjar.com;
    connect-src 'self' https://*.hotjar.com https://*.hotjar.io wss://*.hotjar.com;
    img-src 'self' https://*.hotjar.com https://*.hotjar.io;
    font-src 'self' https://script.hotjar.com;
    style-src 'self' 'unsafe-inline';

Or use nonce/hash-based CSP:

<script nonce="random-nonce-value">
    // Hotjar code here
</script>
Content-Security-Policy: script-src 'nonce-random-nonce-value'

Validation & Testing

Post-Installation Checklist

  • Hotjar script loads without errors
  • hj function is available in console
  • Site shows "Installed" status in Hotjar dashboard
  • Recordings are being captured
  • Heatmaps generate data
  • No console errors
  • Page load performance acceptable
  • Works across all major browsers
  • Works on mobile devices
  • CSP allows Hotjar (if applicable)
  • Privacy/consent implemented

Browser Testing

Test in multiple browsers:

  • Chrome (latest)
  • Firefox (latest)
  • Safari (latest)
  • Edge (latest)
  • Mobile Safari (iOS)
  • Chrome Mobile (Android)

Performance Testing

Measure impact on page load:

const start = performance.now();
// Hotjar loads
window.addEventListener('load', () => {
    const end = performance.now();
    console.log(`Page load with Hotjar: ${end - start}ms`);
});

Target: Hotjar should add less than 100ms to page load


Next Steps: