ngxs-logrocket-plugin
v21.1.2
Published
NGXS plugin for [LogRocket](https://logrocket.com/) that augments LogRocket sessions with actions and state from your NGXS store.
Maintainers
Readme
ngxs-logrocket-plugin
NGXS plugin for LogRocket that augments LogRocket sessions with actions and state from your NGXS store.

Features
- Complete Action Logging - Captures all NGXS actions with their status (Dispatched, Successful, Errored, Canceled)
- State Snapshots - Records state before and after each action
- Optimized Performance - Runs outside Angular zone to prevent unnecessary change detection
- Privacy Controls - Sanitize sensitive data from actions and state
- Flexible Integration - Load LogRocket from npm package or CDN script tag
- SSR Compatible - Safely skips logging during server-side rendering
Installation
npm install ngxs-logrocket-plugin logrocketOr with yarn:
yarn add ngxs-logrocket-plugin logrocketOr with pnpm:
pnpm add ngxs-logrocket-plugin logrocketRequirements
@ngxs/store>= 21.0.0logrocket(peer dependency)- Angular (compatible with your NGXS version)
Usage
Basic Setup
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideStore } from '@ngxs/store';
import { withNgxsLogRocketReduxMiddlewarePlugin } from 'ngxs-logrocket-plugin';
import LogRocket from 'logrocket';
// Initialize LogRocket
LogRocket.init('your-app-id');
export const appConfig: ApplicationConfig = {
providers: [
provideStore(
[
/* your states */
],
withNgxsLogRocketReduxMiddlewarePlugin({
logrocket: () => LogRocket,
}),
),
],
};Loading LogRocket from CDN
If you load LogRocket via a script tag instead of npm:
<!-- index.html -->
<script src="https://cdn.logr-in.com/LogRocket.min.js" crossorigin="anonymous"></script>
<script>
window.LogRocket && window.LogRocket.init('your-app-id');
</script>// app.config.ts
export const appConfig: ApplicationConfig = {
providers: [
provideStore(
[
/* your states */
],
withNgxsLogRocketReduxMiddlewarePlugin({
logrocket: () => window.LogRocket,
}),
),
],
};Lazy-loading Plugin
You can also lazy-load the plugin when LogRocket is needed in your application, for example when a user logs in and LogRocket.init is called:
// somewhere in the app
import { inject, EnvironmentInjector, createEnvironmentInjector, Injector } from '@angular/core';
import { provideStates } from '@ngxs/store';
@Injectable({ providedIn: 'root' })
export class LogRocketService {
private injector = inject(EnvironmentInjector);
async start() {
// Load LogRocket script.
await loadScript('https://cdn.logr-in.com/LogRocket.min.js');
window.LogRocket.init('your-app-id');
// Lazy-load the NGXS plugin.
const { withNgxsLogRocketReduxMiddlewarePlugin } = await import('ngxs-logrocket-plugin');
// Register plugin in child injector so it's available globally.
// This adds the plugin to NGXS without requiring app-level configuration.
createEnvironmentInjector(
[
provideStates(
[],
withNgxsLogRocketReduxMiddlewarePlugin({
logrocket: () => window.LogRocket,
}),
),
],
this.injector,
);
}
}
// Helper function to load external scripts.
function loadScript(src: string): Promise<void> {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.onload = () => resolve();
script.onerror = () => reject(new Error(`Failed to load script: ${src}`));
document.head.appendChild(script);
});
}Configuration
Sanitizing Actions
Remove sensitive data from actions before logging:
withNgxsLogRocketReduxMiddlewarePlugin({
logrocket: () => LogRocket,
actionSanitizer: (action) => {
// Ignore specific actions
if (action.type === '[Auth] Login Success') {
return null; // Action won't be logged
}
// Redact sensitive data
if (action.type === '[User] Update Profile') {
return {
...action,
password: undefined,
creditCard: undefined,
};
}
return action;
},
});Sanitizing State
Remove sensitive data from state snapshots:
withNgxsLogRocketReduxMiddlewarePlugin({
logrocket: () => LogRocket,
stateSanitizer: (state) => {
return {
...state,
auth: {
...state.auth,
token: undefined, // Remove auth token
password: undefined,
},
payment: undefined, // Remove entire payment state
};
},
});Using Angular Injection in Sanitizers
Both logrocket, stateSanitizer, and actionSanitizer run in injection context, allowing you to use Angular's inject():
import { inject } from '@angular/core';
import { MySecurityService } from './my-security.service';
withNgxsLogRocketReduxMiddlewarePlugin({
logrocket: () => LogRocket,
stateSanitizer: (state) => {
const security = inject(MySecurityService);
return security.sanitizeState(state);
},
actionSanitizer: (action) => {
const security = inject(MySecurityService);
return security.shouldLogAction(action) ? action : null;
},
});Action Status Types
The plugin logs actions with the following statuses:
| Status | Description |
| ------------ | ------------------------------------------------------ |
| DISPATCHED | Action has been dispatched |
| SUCCESSFUL | Action handler completed successfully |
| ERRORED | Action handler threw an error |
| CANCELED | Action was canceled by another action of the same type |
Example in LogRocket:
[Countries] Load countries (DISPATCHED)
[Countries] Load countries (SUCCESSFUL)
[Auth] Login (DISPATCHED)
[Auth] Login (ERRORED)How It Works
The plugin integrates with NGXS as a middleware and leverages LogRocket's Redux middleware under the hood:
- Intercepts all NGXS actions before they're processed
- Logs action dispatch with current state
- Captures action completion (success, error, or cancellation)
- Compresses actions and state using LogRocket's binary format
- Performs state diffs to minimize network data
All logging operations run outside the Angular zone to prevent triggering unnecessary change detection cycles.
Viewing Logs in LogRocket
Once configured, you can view NGXS actions in the LogRocket dashboard:
- Open a session in LogRocket
- Navigate to the "Redux" tab
- Browse actions and state changes
- Click an action to see state before and after
Performance Considerations
- Zone Optimization: All LogRocket operations run outside Angular's zone
- Data Compression: Actions and state are compressed using binary format
- State Diffing: Only state changes are transmitted, not full snapshots
- Error Handling: LogRocket errors are caught and logged without breaking your app
- SSR Safe: Automatically skips logging on server to prevent errors
TypeScript Support
Full TypeScript support is included. The plugin exports all necessary types:
import type { NgxsLogRocketReduxMiddlewareOptions } from 'ngxs-logrocket-plugin';Troubleshooting
Actions Not Appearing in LogRocket
- Verify LogRocket is initialized before NGXS
- Check that the plugin is registered with
provideStore - Ensure you're not returning
nullfromactionSanitizer
Performance Issues
- Use
actionSanitizerto filter high-frequency actions - Sanitize large state objects to reduce payload size
- Verify you're using the factory pattern
() => LogRocket(not direct reference)
License
MIT © arturovt
Related Projects
- logrocket - LogRocket JavaScript SDK
- @ngxs/store - NGXS State Management
- logrocket-ngrx - NgRx middleware for LogRocket
Version Compatibility
This package follows the major version of @ngxs/store:
| ngxs-logrocket-plugin | @ngxs/store | | --------------------- | ----------- | | 21.x.x | >=21.0.0 |
