LogRocket Data Layer Setup | OpsBlu Docs

LogRocket Data Layer Setup

Configure data layer, user properties, and custom metadata for LogRocket session enrichment.

Data Layer Approach for LogRocket

LogRocket doesn't require a traditional data layer like Google Tag Manager, but does support rich user identification and custom session properties that serve a similar purpose. The goal is to enrich sessions with contextual data that makes them searchable, actionable, and valuable for debugging and support.

User Identification as Data Layer

User identification in LogRocket serves as the primary "data layer" for enriching sessions with user context.

Core Strategy:

  • Call LogRocket.identify() after user authentication
  • Include user properties that help segment, search, and understand sessions
  • Update properties when user context changes (e.g., after upgrade, profile update)

Basic Implementation:

import LogRocket from 'logrocket';

// After user logs in
function handleLogin(user) {
  LogRocket.identify(user.id, {
    // Identity
    name: user.name,
    email: user.email,

    // Subscription/Account
    plan: user.subscription.plan,
    accountType: user.account.type,

    // Segmentation
    userRole: user.role,
    companyName: user.company,

    // Metadata
    signupDate: user.createdAt,
    lastLogin: new Date().toISOString()
  });
}

Structured User Properties

Define consistent user property structure across your application for searchability and clarity.

Recommended Structure:

LogRocket.identify(userId, {
  // --- Identity Properties ---
  name: 'Jane Doe',
  email: 'jane@example.com',

  // --- Account Properties ---
  accountId: 'acc_12345',
  accountType: 'team', // individual, team, enterprise
  seats: 5,

  // --- Subscription Properties ---
  plan: 'Professional',
  planTier: 'paid', // free, trial, paid
  billingCycle: 'annual', // monthly, annual
  mrr: 199,
  subscriptionStatus: 'active', // active, past_due, canceled
  trialEndDate: '2024-02-01',

  // --- Segmentation Properties ---
  userRole: 'Admin', // Admin, Member, Viewer
  industry: 'SaaS',
  companySize: '50-100',
  region: 'North America',

  // --- Behavioral Properties ---
  lifetimeValue: 2388,
  totalLogins: 47,
  lastActiveDate: '2024-01-20',
  featureUsageCount: {
    reporting: 23,
    api: 12,
    integrations: 5
  },

  // --- Flags & Experiments ---
  betaTester: true,
  experimentGroup: 'variant-b',
  featureFlags: {
    newDashboard: true,
    advancedReporting: false
  }
});

Session-Level Custom Properties

In addition to user properties, you can track session-level metadata using custom events and tags.

Implementation:

import LogRocket from 'logrocket';

// Track session metadata on page load
LogRocket.track('Session Started', {
  // Environment
  environment: 'production',
  appVersion: '2.1.0',
  deploymentRegion: 'us-east-1',

  // Context
  landingPage: window.location.pathname,
  referrer: document.referrer,
  utmSource: new URLSearchParams(window.location.search).get('utm_source'),
  utmCampaign: new URLSearchParams(window.location.search).get('utm_campaign'),

  // Device
  browserLanguage: navigator.language,
  screenResolution: `${window.screen.width}x${window.screen.height}`,

  // Feature flags (if using feature flag system)
  enabledFeatures: getEnabledFeatures()
});

Dynamic Property Updates

Update user properties when context changes during a session.

Example: Subscription Upgrade

function handleSubscriptionUpgrade(newPlan) {
  // Update LogRocket user properties
  LogRocket.identify(currentUser.id, {
    plan: newPlan.name,
    planTier: 'paid',
    mrr: newPlan.price,
    upgradeDate: new Date().toISOString()
  });

  // Track the upgrade event
  LogRocket.track('Subscription Upgraded', {
    oldPlan: currentUser.plan,
    newPlan: newPlan.name,
    priceDifference: newPlan.price - currentUser.mrr
  });
}

Example: Feature Flag Change

function updateFeatureFlags(flags) {
  LogRocket.identify(currentUser.id, {
    featureFlags: flags
  });

  LogRocket.track('Feature Flags Updated', {
    flags: Object.keys(flags).filter(key => flags[key])
  });
}

Integration with State Management

LogRocket can capture application state from Redux, Vuex, or NgRx, providing deep context without manual data layer setup.

Redux Integration:

import { createStore, applyMiddleware } from 'redux';
import LogRocket from 'logrocket';

const store = createStore(
  rootReducer,
  applyMiddleware(
    LogRocket.reduxMiddleware({
      // Automatically captures all Redux state
      // Sanitize sensitive state fields
      stateSanitizer: state => ({
        ...state,
        auth: {
          ...state.auth,
          token: 'REDACTED'
        }
      })
    })
  )
);

Vuex Integration:

import LogRocket from 'logrocket';
import Vuex from 'vuex';

const store = new Vuex.Store({
  plugins: [LogRocket.vuexPlugin()],
  // All Vuex state and mutations are captured
});

NgRx Integration:

import LogRocket from 'logrocket';

StoreModule.forRoot(reducers, {
  metaReducers: [LogRocket.ngrxMiddleware()]
  // All NgRx state and actions are captured
});

Searchable Properties Strategy

Design your property schema to enable powerful session search in LogRocket dashboard.

Search-Friendly Properties:

LogRocket.identify(user.id, {
  // Email - searchable in LogRocket UI
  email: user.email,

  // Plan - filter sessions by subscription tier
  plan: user.plan, // 'Free', 'Pro', 'Enterprise'

  // User role - segment by permission level
  role: user.role, // 'Admin', 'Member', 'Viewer'

  // Company - group sessions by organization
  company: user.company,

  // Region - filter by geography
  region: user.region,

  // Custom tags - arbitrary categorization
  tags: ['high-value', 'support-priority', 'beta-tester']
});

Search Examples in LogRocket Dashboard:

  • Find all sessions where plan = "Enterprise"
  • Search for sessions from company = "Acme Corp"
  • Filter sessions where role = "Admin"
  • Find sessions with tags containing "support-priority"

Contextual Event Properties

Enrich custom events with contextual properties that provide debugging insights.

Example: Purchase Event with Context

LogRocket.track('Purchase Completed', {
  // Transaction
  orderId: 'ORD-12345',
  amount: 299.99,
  currency: 'USD',

  // Products
  itemCount: 3,
  productIds: ['prod-1', 'prod-2', 'prod-3'],
  categories: ['Electronics', 'Accessories'],

  // Discounts
  discountCode: 'SAVE20',
  discountAmount: 60,

  // Payment
  paymentMethod: 'stripe',
  paymentStatus: 'succeeded',

  // Context
  checkoutDuration: 45, // seconds
  firstPurchase: true,
  purchaseSource: 'web', // web, mobile, api

  // User State (at time of purchase)
  userPlan: currentUser.plan,
  userTenure: getUserTenureDays()
});

Environment-Specific Properties

Tag sessions with environment and version metadata for debugging production issues.

Implementation:

LogRocket.init('your-app/project', {
  release: process.env.APP_VERSION || '1.0.0',
  console: { isEnabled: true },
  network: { isEnabled: true }
});

// Set environment properties on all users
LogRocket.identify(user.id, {
  name: user.name,
  email: user.email,

  // Environment metadata
  environment: process.env.NODE_ENV, // production, staging, development
  appVersion: process.env.APP_VERSION,
  buildNumber: process.env.BUILD_NUMBER,
  deploymentDate: process.env.DEPLOY_DATE
});

Privacy Considerations for Data Layer

Ensure your data layer doesn't expose sensitive information.

Sanitization Strategy:

// Helper to sanitize user data
function getSafeUserProperties(user) {
  return {
    // Safe properties
    name: user.name,
    email: user.email,
    plan: user.plan,
    role: user.role,

    // Sanitize sensitive fields
    // DON'T include: SSN, credit cards, passwords, API keys

    // Hash or anonymize if needed
    companyId: hashId(user.companyId), // hash instead of raw ID

    // Aggregate instead of raw
    lastLoginDate: user.lastLogin.split('T')[0] // date only, not timestamp
  };
}

LogRocket.identify(user.id, getSafeUserProperties(user));

Validation & Testing

Verify User Properties:

// After identification, check properties in console
LogRocket.getSessionURL(sessionURL => {
  console.log('Session URL:', sessionURL);
  console.log('User identified with properties');

  // Visit session in LogRocket dashboard to verify properties appear
});

Test Property Updates:

// Initial identification
LogRocket.identify('user-123', { plan: 'Free' });

// After upgrade
LogRocket.identify('user-123', { plan: 'Pro' });

// Properties should update in LogRocket dashboard

Validate Event Properties:

// Track test event
LogRocket.track('Test Event', {
  testProperty: 'test value',
  timestamp: new Date().toISOString()
});

// Check session replay for event in timeline with properties

Best Practices

Do:

  • Identify users immediately after authentication
  • Use consistent property naming across application
  • Include properties that help search and filter sessions
  • Update properties when user context changes
  • Document property schema for team reference

Don't:

  • Include PII without sanitization (SSN, credit cards)
  • Send excessive properties (keep under 20 per user)
  • Use inconsistent naming (camelCase vs snake_case)
  • Forget to update properties on state changes
  • Include large objects or arrays as properties

Example: Complete Data Layer Setup

Initialization:

// app.js
import LogRocket from 'logrocket';

LogRocket.init('your-app/production', {
  release: process.env.APP_VERSION,
  console: { isEnabled: true },
  network: { isEnabled: true }
});

User Identification (after login):

// auth.js
function handleLogin(user) {
  LogRocket.identify(user.id, {
    // Identity
    name: user.name,
    email: user.email,

    // Subscription
    plan: user.subscription.plan,
    mrr: user.subscription.mrr,

    // Segmentation
    role: user.role,
    company: user.company,

    // Environment
    environment: process.env.NODE_ENV,
    appVersion: process.env.APP_VERSION
  });

  LogRocket.track('User Logged In', {
    loginMethod: 'email',
    mfaEnabled: user.mfaEnabled
  });
}

Event Tracking (on key actions):

// features.js
function trackFeatureUsage(featureName) {
  LogRocket.track('Feature Used', {
    featureName,
    userPlan: currentUser.plan,
    userRole: currentUser.role,
    timestamp: new Date().toISOString()
  });
}

Additional Resources: