Sentry Zustand Middleware

4.3.0 · active · verified Wed Apr 22

sentry-zustand-middleware is a specialized middleware for Zustand stores designed to automatically log state changes and actions to Sentry. This package is currently at version 4.3.0 and typically follows the release cycles of its peer dependencies, Zustand and Sentry, to ensure compatibility. Its core function is to capture the state snapshots and the actions that modify them, providing enhanced debugging capabilities and visibility into application state flow during error reporting. A key differentiator is its optional `stateTransformer` function, which allows developers to clean, filter, or obfuscate sensitive data from the Zustand state before it is sent to Sentry, preventing oversharing of private information. It provides a direct integration without manual Sentry calls within every action or state update.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic integration of `sentry-zustand-middleware` with a Zustand store, logging state changes and actions to Sentry (assuming Sentry is initialized).

import create from 'zustand';
import sentryMiddleware from 'sentry-zustand-middleware';

// Ensure Sentry is initialized elsewhere in your application entry point
// For example:
// import * as Sentry from '@sentry/browser';
// Sentry.init({ dsn: process.env.SENTRY_DSN ?? '' });

interface BearState {
  bears: number;
  increase: (by: number) => void;
  decrease: (by: number) => void;
  logSomething: (message: string) => void;
}

const useStore = create<BearState>()(
  sentryMiddleware((set) => ({
    bears: 0,
    increase: (by) => {
      set((state) => ({ bears: state.bears + by }), false, 'increaseBears');
    },
    decrease: (by) => {
      set((state) => ({ bears: state.bears - by }), false, 'decreaseBears');
    },
    logSomething: (message) => {
      // This action will also be logged by the middleware
      console.log(message);
    }
  })),
);

// Example usage (ensure Sentry is initialized for actual logging)
const store = useStore.getState();
store.increase(5);
store.decrease(2);

console.log('Current bears:', useStore.getState().bears);

view raw JSON →