LogRocket Install / Embed Tag or SDK | OpsBlu Docs

LogRocket Install / Embed Tag or SDK

Deployment approach for installing LogRocket's SDK across web applications with privacy and performance considerations.

Deployment Strategy

  • Install LogRocket SDK via npm for modern JavaScript applications; initialize as early as possible in the lifecycle.
  • Configure privacy settings during initialization: input sanitization, network filtering, CSS privacy classes.
  • Consider conditional initialization based on environment (production only) or user type (authenticated users only).
  • Implement first-party proxy to reduce ad blocker interference if sessions are being lost.
  • Install via npm for React, Vue, Angular, or any modern JavaScript framework.
  • Import and initialize in application entry point before any user interactions.
  • Configure app ID per environment using environment variables.
  • Enable privacy controls and state management plugins during initialization.

Installation:

npm install logrocket

Basic Initialization:

import LogRocket from 'logrocket';

LogRocket.init('your-app/project-name');

Environment-Specific Initialization:

import LogRocket from 'logrocket';

const appId = process.env.NODE_ENV === 'production'
  ? 'your-app/production'
  : 'your-app/development';

if (process.env.NODE_ENV === 'production') {
  LogRocket.init(appId, {
    release: process.env.APP_VERSION,
    console: {
      isEnabled: true,
      shouldAggregateConsoleErrors: true
    },
    network: {
      isEnabled: true
    }
  });
}

CDN / Script Tag Installation

  • Load LogRocket via CDN for static sites or applications without build tools.
  • Place script tag in HTML head before other scripts to ensure early initialization.
  • Use async loading to avoid blocking page rendering.

CDN Installation:

<script src="https://cdn.lr-in-prod.com/LogRocket.min.js" crossorigin="anonymous"></script>
<script>
  window.LogRocket && LogRocket.init('your-app/project-name');
</script>

Async Loading Pattern:

<script>
  (function() {
    var script = document.createElement('script');
    script.src = 'https://cdn.lr-in-prod.com/LogRocket.min.js';
    script.async = true;
    script.onload = function() {
      LogRocket.init('your-app/project-name');
    };
    document.head.appendChild(script);
  })();
</script>

Tag Manager Deployment

  • Deploy via Google Tag Manager or similar TMS with app ID variable per environment.
  • Fire initialization tag early (DOM Ready or earlier) before user interaction tags.
  • Store configuration options in TMS variables for easier updates without code deployment.

GTM Custom HTML Tag:

<script src="https://cdn.lr-in-prod.com/LogRocket.min.js" crossorigin="anonymous"></script>
<script>
  window.LogRocket && LogRocket.init('{{LogRocket App ID}}', {
    release: '{{App Version}}',
    console: { isEnabled: true },
    network: { isEnabled: true }
  });
</script>

Trigger: Page View - All Pages (fire early)

Framework-Specific Integration

React Applications

// src/index.js or src/App.js
import React from 'react';
import ReactDOM from 'react-dom';
import LogRocket from 'logrocket';
import setupLogRocketReact from 'logrocket-react';
import App from './App';

// Initialize LogRocket before React
LogRocket.init('your-app/project-name');
setupLogRocketReact(LogRocket);

ReactDOM.render(<App />, document.getElementById('root'));

Vue Applications

// src/main.js
import { createApp } from 'vue';
import LogRocket from 'logrocket';
import App from './App.vue';

// Initialize LogRocket before Vue
LogRocket.init('your-app/project-name');

createApp(App).mount('#app');

Angular Applications

// src/main.ts
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import LogRocket from 'logrocket';
import { AppModule } from './app/app.module';

// Initialize LogRocket before Angular
LogRocket.init('your-app/project-name');

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));

Next.js Applications

// pages/_app.js
import LogRocket from 'logrocket';
import { useEffect } from 'react';

function MyApp({ Component, pageProps }) {
  useEffect(() => {
    // Initialize on client-side only
    if (typeof window !== 'undefined') {
      LogRocket.init('your-app/project-name');
    }
  }, []);

  return <Component {...pageProps} />;
}

export default MyApp;

Privacy Configuration

  • Enable input sanitization to automatically redact sensitive form fields.
  • Configure network request/response sanitizers to remove authorization tokens and sensitive payloads.
  • Use CSS privacy classes (lr-hide, lr-mask, lr-block) on elements containing sensitive data.
  • Set up state management sanitizers when using Redux, Vuex, or NgRx plugins.

Privacy Settings:

LogRocket.init('your-app/project-name', {
  dom: {
    inputSanitizer: true,  // Auto-sanitize all inputs
    textSanitizer: true,   // Sanitize text content
    baseHref: window.location.origin
  },
  network: {
    requestSanitizer: request => {
      // Remove authorization headers
      if (request.headers['Authorization']) {
        request.headers['Authorization'] = 'REDACTED';
      }

      // Remove sensitive request body fields
      if (request.body) {
        try {
          const body = JSON.parse(request.body);
          if (body.password) body.password = 'REDACTED';
          if (body.ssn) body.ssn = 'REDACTED';
          request.body = JSON.stringify(body);
        } catch (e) {
          // Body is not JSON, leave as-is
        }
      }

      return request;
    },
    responseSanitizer: response => {
      // Remove sensitive response fields
      if (response.body) {
        try {
          const body = JSON.parse(response.body);
          if (body.creditCard) body.creditCard = 'REDACTED';
          if (body.apiKey) body.apiKey = 'REDACTED';
          response.body = JSON.stringify(body);
        } catch (e) {
          // Body is not JSON, leave as-is
        }
      }

      return response;
    }
  },
  console: {
    isEnabled: true,
    shouldAggregateConsoleErrors: true
  }
});

CSS Privacy Classes:

<!-- Text will be hidden in replays -->
<div class="lr-hide">
  Sensitive customer information here
</div>

<!-- Input value will be masked as *** -->
<input type="text" class="lr-mask" placeholder="SSN" />

<!-- Element completely excluded from recording -->
<div class="lr-block">
  Completely hidden from LogRocket
</div>

Conditional & Sampled Recording

  • Implement conditional initialization to record only production traffic or authenticated users.
  • Use sampling to record a percentage of sessions if volume is high and costs are a concern.
  • Gate initialization behind user consent if required for privacy compliance (GDPR, CCPA).

Conditional Recording (Production Only):

if (process.env.NODE_ENV === 'production') {
  LogRocket.init('your-app/production');
}

Authenticated Users Only:

// Don't initialize on page load
// Initialize after authentication
function handleLogin(user) {
  if (!window.LogRocket.sessionURL) {
    LogRocket.init('your-app/project-name');
  }

  LogRocket.identify(user.id, {
    email: user.email,
    name: user.name,
    plan: user.plan
  });
}

Session Sampling (50% of sessions):

const shouldRecord = Math.random() < 0.5;

if (shouldRecord) {
  LogRocket.init('your-app/project-name');
}

Consent-Based Recording:

// Wait for user consent
function handleConsentGranted() {
  LogRocket.init('your-app/project-name');
}

// Check consent on page load
if (hasUserConsent()) {
  LogRocket.init('your-app/project-name');
}

First-Party Proxy Setup

  • Implement first-party proxy to route LogRocket requests through your domain and reduce ad blocker interference.
  • Configure proxy endpoint in LogRocket initialization to point to your domain.
  • Requires server-side proxy configuration to forward requests to LogRocket's ingest endpoints.

Client Configuration:

LogRocket.init('your-app/project-name', {
  uploadURL: 'https://your-domain.com/logrocket-proxy',
  ingestURL: 'https://your-domain.com/logrocket-ingest'
});

Server-Side Proxy (Example with Express):

const express = require('express');
const fetch = require('node-fetch');
const app = express();

app.use('/logrocket-proxy', async (req, res) => {
  const response = await fetch('https://r.lr-ingest.com/i', {
    method: req.method,
    headers: req.headers,
    body: req.body
  });

  const data = await response.text();
  res.send(data);
});

app.listen(3000);

Validation Checklist

  • Verify LogRocket session URL is generated and accessible in browser console: LogRocket.sessionURL
  • Confirm sessions appear in LogRocket dashboard Live View within seconds of initialization.
  • Test privacy controls: ensure sensitive inputs and network requests are sanitized in session replays.
  • Validate state management integration if using Redux, Vuex, or NgRx plugins.
  • Check browser console for any LogRocket errors or warnings.

Console Verification:

// Open browser console and run:
console.log('LogRocket Session:', LogRocket.sessionURL);
// Should output: https://app.logrocket.com/your-app/sessions/abc123

// If null or undefined, check:
// 1. LogRocket.init() was called
// 2. Correct app ID was used
// 3. No ad blockers or network blocks
// 4. No JavaScript errors before initialization

Configuration Recommendations

Environment Scoping: Initialize LogRocket only in production: if (window.location.hostname === 'yourdomain.com') { LogRocket.init('app-id'); }. Alternatively, use separate LogRocket projects for staging and production. Avoid initializing in development to save session quota.

User Identification: Call LogRocket.identify(userId, { name, email, plan }) immediately after authentication. Include user properties that help support and product teams find relevant sessions (plan tier, company name, role). Never include passwords or tokens in identify traits.

Source Maps: Upload source maps during your CI/CD build step using LogRocket's CLI: npx @logrocket/cli upload --release=VERSION ./dist. This deobfuscates JavaScript errors in session replays. Configure release versions to match your deployment tags.

Privacy Controls: Use LogRocket.init('app-id', { network: { requestSanitizer, responseSanitizer } }) to strip auth headers and PII from network captures. Add data-private attribute to DOM elements containing sensitive information. Configure input sanitization to mask all inputs by default: dom: { inputSanitizer: true }.

Ad Blocker Bypass: If sessions are blocked, set up a first-party proxy. Route cdn.lr-in.com, cdn.lr-ingest.io, and cdn.lr-intake.io through your domain. LogRocket provides proxy setup documentation for Nginx, CloudFront, and Cloudflare.