LogRocket JavaScript SDK
LogRocket's JavaScript SDK, currently at version 12.1.0, provides a comprehensive solution for front-end monitoring, session replay, and product analytics. It allows development and product teams to reproduce user issues by replaying sessions pixel-perfectly, alongside integrated technical context such as console logs, network requests, and Redux state changes. This SDK differentiates itself by its strong focus on engineering-grade debugging, offering detailed diagnostic insights into client-side errors and performance issues. While a fixed release cadence isn't explicitly published, the package undergoes regular updates with new features and improvements. A key feature is its ability to automatically detect user frustration signals like rage clicks and dead clicks, and its robust data privacy features include default obfuscation of sensitive information, with configurable options for granular control over what data is collected and sent to the servers. It integrates with various tools like Sentry, Jira, and Google Analytics to streamline developer workflows and provide a holistic view of user experience.
Common errors
-
ReferenceError: navigator is not defined
cause Attempting to initialize LogRocket or use its methods in a server-side rendering (SSR) environment without a client-side check.fixEnsure `LogRocket.init()` and related calls are executed only in the browser environment. For React, this typically means inside a `useEffect` hook or using dynamic imports with `ssr: false`. Example: `if (typeof window !== 'undefined') { LogRocket.init(...); }` -
Sessions not appearing in LogRocket dashboard / No data being recorded.
cause Common causes include incorrect App ID, network requests blocked by ad-blockers or content security policies (CSPs), LogRocket not initialized, or excessive privacy/redaction settings.fixVerify the App ID passed to `LogRocket.init()`. Check browser console for any errors or blocked network requests related to LogRocket. Review your Content Security Policy to ensure `cdn.logr-in.com` is allowed. Temporarily disable strict privacy configurations to isolate the issue. Ensure `LogRocket.init()` is called only once and early in your application lifecycle. -
Redux actions or state are not being captured/displayed in session replays.
cause The `@logrocket/redux` middleware is either not installed, not applied, or applied in the wrong order (not as the last middleware) in your Redux store configuration. Very large Redux actions can also be automatically disabled to prevent performance issues.fixInstall `@logrocket/redux` (`npm install @logrocket/redux`). Ensure `reduxMiddleware` is imported and added as the *last* middleware in `applyMiddleware` when creating your Redux store. Check LogRocket's configuration for any limits on action size or frequency.
Warnings
- gotcha LogRocket.init() must always be called client-side (in the browser). Attempting to call it in a server-side (Node.js) environment will result in errors and prevent sessions from being recorded.
- gotcha Sensitive data (e.g., passwords, credit card numbers, PII) may be captured by default if not explicitly redacted. While LogRocket obfuscates some text by default, it is crucial to review and configure privacy settings for visual data and network requests.
- gotcha When using LogRocket with Redux, ensure the `reduxMiddleware` is the *last* middleware applied in your Redux store setup. If placed earlier, it may not accurately capture the final state or actions after subsequent middleware have processed them.
- breaking While the core LogRocket web SDK generally maintains strong backward compatibility, major version upgrades (e.g., v1.x to v2.x, or similar future changes) may introduce breaking changes, especially around configuration options, API signatures, or integration plugins. Mobile SDKs (e.g., React Native) have had specific breaking changes related to view capture and redaction in their 1.x and 2.x lines.
Install
-
npm install logrocket -
yarn add logrocket -
pnpm add logrocket
Imports
- LogRocket
const LogRocket = require('logrocket');import LogRocket from 'logrocket';
- init
import { init } from 'logrocket'; init('YOUR_APP_ID');import LogRocket from 'logrocket'; LogRocket.init('YOUR_APP_ID'); - identify
import { identify } from 'logrocket'; identify('user-id', { ... });import LogRocket from 'logrocket'; LogRocket.identify('user-id', { name: 'John Doe', email: 'john.doe@example.com' }); - reduxMiddleware
import { reduxMiddleware } from 'logrocket'; // ...or... import LogRocket from 'logrocket'; const store = createStore(rootReducer, applyMiddleware(reduxMiddleware));import LogRocket from 'logrocket'; import { createStore, applyMiddleware } from 'redux'; import { reduxMiddleware } from '@logrocket/redux'; const store = createStore(rootReducer, applyMiddleware(LogRocket.reduxMiddleware));
Quickstart
import LogRocket from 'logrocket';
import { reduxMiddleware } from '@logrocket/redux';
import { createStore, applyMiddleware, combineReducers } from 'redux';
interface AppState {
counter: number;
message: string;
}
const counterReducer = (state = 0, action: { type: string }) => {
switch (action.type) {
case 'INCREMENT': return state + 1;
case 'DECREMENT': return state - 1;
default: return state;
}
};
const messageReducer = (state = '', action: { type: string, payload?: string }) => {
switch (action.type) {
case 'SET_MESSAGE': return action.payload || '';
default: return state;
}
};
const rootReducer = combineReducers<AppState>({
counter: counterReducer,
message: messageReducer
});
// Replace with your actual LogRocket App ID
const LOGROCKET_APP_ID = process.env.LOGROCKET_APP_ID || 'your/app-id';
// Initialize LogRocket
LogRocket.init(LOGROCKET_APP_ID, {
// Optional: Configure specific options
console: {
isEnabled: true,
shouldAggregateConsoleErrors: true,
},
network: {
isEnabled: true,
requestSanitizer: (request) => {
// Redact sensitive headers, e.g., Authorization
if (request.headers?.Authorization) {
request.headers.Authorization = 'Bearer [Redacted]';
}
return request;
},
},
dom: {
// Optional: Redact elements containing sensitive data
// For example, an element with data-lr-hide will not be recorded
baseHref: '/', // Specify if your app uses a base href
}
});
// Identify the user after initialization
LogRocket.identify('unique-user-id-123', {
name: 'Jane Doe',
email: 'jane.doe@example.com',
subscriptionType: 'premium',
// Custom user traits for filtering sessions
'user-type': 'admin'
});
// Integrate Redux middleware (must be after LogRocket.init)
const store = createStore(rootReducer, applyMiddleware(reduxMiddleware));
// Simulate some actions
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'SET_MESSAGE', payload: 'User clicked increment twice' });
try {
throw new Error('This is a test error to see in LogRocket!');
} catch (error) {
LogRocket.error(error);
}
console.log('LogRocket initialized and user identified. Check your dashboard for the session.');
// Example of sending a custom event
LogRocket.track('Product View', { productId: 'ABC-123', category: 'Electronics' });
// This is client-side code, typically run in a browser environment.
// Ensure to include your actual LogRocket App ID from your project settings.