# Write typed middleware

Wrap a state creator to intercept updates and add a typed property to the store API without losing middleware composition.

Use custom middleware when you need behavior beyond the shipped middleware. For debugging, start with [`devtools`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-middleware#devtools); for draft-style updates, use [`immer`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-middleware-immer#immer). This page goes below those helpers because you are implementing a new state-creator wrapper.

The example renders a counter and a store-level label. Both the action button and the imperative-update button increase the counter and log the resulting state in the browser console.

Start from the project in the [React quick start](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/react-quick-start). Zustand is already installed there; this example adds no dependencies. In another React TypeScript project, install it with:

```bash
npm install zustand
```

## 1. Intercept action and imperative updates

Preserve the [`StateCreator`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#statecreator) mutator lists, whose entries use [`StoreMutatorIdentifier`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#storemutatoridentifier), when wrapping the initializer described in [How Zustand works](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/how-zustand-works#1-a-store-holds-state-independently-of-react).

Add `src/logger.ts`. Following the authors' logger recipe, wrap both `set` and `store.setState`: wrapping only `set` misses calls made through the store's public `setState` method.

```ts title="src/logger.ts"
import type { StateCreator, StoreMutatorIdentifier } from 'zustand'

type Logger = <
  T,
  Mps extends [StoreMutatorIdentifier, unknown][] = [],
  Mcs extends [StoreMutatorIdentifier, unknown][] = [],
>(
  creator: StateCreator<T, Mps, Mcs>,
  name?: string,
) => StateCreator<T, Mps, Mcs>

type LoggerImpl = <T>(
  creator: StateCreator<T, [], []>,
  name?: string,
) => StateCreator<T, [], []>

const loggerImpl: LoggerImpl = (creator, name) => (set, get, store) => {
  const loggedSet: typeof set = (...args) => {
    set(...(args as Parameters<typeof set>))
    console.log(name ? `${name}:` : 'state:', get())
  }

  const setState = store.setState
  store.setState = (...args) => {
    setState(...(args as Parameters<typeof setState>))
    console.log(name ? `${name}:` : 'state:', store.getState())
  }

  return creator(loggedSet, get, store)
}

export const logger = loggerImpl as Logger
```

Each wrapper forwards the update before logging, so the console shows the state after that update. Capture `store.setState` before replacing it to avoid calling the wrapper recursively. The `Parameters` assertions forward the overloaded setter's arguments; they do not change the update or its replacement flag.

The public `Logger` signature keeps `Mps` and `Mcs` unchanged. The implementation uses the unmodified setter type, while the exported signature preserves the surrounding middleware's mutator lists.

## 2. Describe a store API addition

Add a `foo` property to the store API, not to its state. Register its type through [`StoreMutators`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#storemutators). [`Mutate`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#mutate) applies a mutator list to an API type; [`StoreApi`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#storeapi) supplies the base API.

Add `src/foo.ts`. This follows the authors' store-type-changing middleware recipe: append the addition to the wrapped creator's input list, then prepend it to the returned creator's output list.

```ts title="src/foo.ts"
import type {
  Mutate,
  StateCreator,
  StoreApi,
  StoreMutatorIdentifier,
} from 'zustand/vanilla'

type Foo = <
  T,
  A,
  Mps extends [StoreMutatorIdentifier, unknown][] = [],
  Mcs extends [StoreMutatorIdentifier, unknown][] = [],
>(
  creator: StateCreator<T, [...Mps, ['foo', A]], Mcs>,
  value: A,
) => StateCreator<T, Mps, [['foo', A], ...Mcs]>

declare module 'zustand/vanilla' {
  interface StoreMutators<S, A> {
    foo: Omit<S, 'foo'> & { foo: A }
  }
}

type FooImpl = <T, A>(
  creator: StateCreator<T, [], []>,
  value: A,
) => StateCreator<T, [], [['foo', A]]>

const fooImpl: FooImpl = (creator, value) => (set, get, originalStore) => {
  type T = ReturnType<typeof creator>
  type A = typeof value

  const store = originalStore as Mutate<StoreApi<T>, [['foo', A]]>
  store.foo = value
  return creator(set, get, originalStore)
}

export const foo = fooImpl as Foo
```

The declaration describes the type change; `store.foo = value` performs the corresponding runtime change before the wrapped creator runs. The assertion connects that runtime assignment to the registered mutator type. It does not create the property by itself.

For `foo(creator, 'typed middleware')`, the resulting store exposes a string-valued `foo`. The wrapped creator also receives that addition in its store argument. Other input and output mutators remain in their original lists.

## 3. Compose the wrappers on a React store

Add `src/middleware-store.ts`. Use [`create`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#create) with `create<CounterState>()(...)`: annotate the state while allowing the middleware's output mutators to be inferred. Keep the composition directly inside `create`, following the authors' TypeScript examples.

```ts title="src/middleware-store.ts"
import { create } from 'zustand'
import { devtools } from 'zustand/middleware'
import { foo } from './foo'
import { logger } from './logger'

type CounterState = {
  count: number
  increment: () => void
}

export const useMiddlewareStore = create<CounterState>()(
  devtools(
    logger(
      foo(
        (set) => ({
          count: 0,
          increment: () => set((state) => ({ count: state.count + 1 })),
        }),
        'typed middleware',
      ),
      'counter',
    ),
    { name: 'Typed middleware counter' },
  ),
)
```

The resulting hook retains the counter state, the store methods, and the string-valued `foo` addition. Keep `devtools` outside middleware that changes `setState`'s type so its additional setter type parameter is preserved. See [Split a store into slices](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/split-store-into-slices) for composition order when combining slices.

## 4. Mount and test both update paths

Add `src/MiddlewareCounter.tsx` to compare the wrapped action and imperative update paths; [the quick start](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/react-quick-start#3-select-state-and-an-action-in-a-component) covers the underlying counter rendering pattern.

```tsx title="src/MiddlewareCounter.tsx"
import { useMiddlewareStore } from './middleware-store'

export default function MiddlewareCounter() {
  const count = useMiddlewareStore((state) => state.count)

  return (
    <section style={{ minHeight: 400 }}>
      <h1>{useMiddlewareStore.foo.toUpperCase()}</h1>
      <p aria-live="polite">Count: {count}</p>
      <button type="button" onClick={() => useMiddlewareStore.getState().increment()}>
        Action +1
      </button>
      <button
        type="button"
        onClick={() => useMiddlewareStore.setState((state) => ({ count: state.count + 1 }))}
      >
        Imperative +1
      </button>
      <p>Open the browser console to inspect each update.</p>
    </section>
  )
}
```

Replace `src/Counter.tsx` with this re-export to display the middleware example through the unchanged entry file from [Mount the counter](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/react-quick-start#4-mount-the-counter):

```tsx title="src/Counter.tsx"
export { default } from './MiddlewareCounter'
```

Run `npm run build`, then `npm run dev` and open Vite's local URL. The page displays `TYPED MIDDLEWARE`, `Count: 0`, and two update buttons. Click either button: the count increases and the console receives the resulting state prefixed with `counter:`. With the Redux DevTools browser extension installed, inspect this store under **Typed middleware counter**.

The label is a fixed store API property, not reactive state. Keep values that must trigger rendering in the state and select them through the hook, as the counter does.

## Options and type parameters

These custom wrappers accept positional arguments rather than an options object.

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `logger`'s `name` | `string` | Omitted; falls back to `state:` | Prefixes each console entry; the composed sample passes `counter` and logs `counter:`. |
| `foo`'s `value` | Generic `A` | Required | Supplies the value assigned to the store API's `foo`. |

For `StateCreator<T, Mps, Mcs, U>`, `T` is the complete state, `Mps` types the API supplied to the creator, `Mcs` records its outward API mutations, and `U` is its return type, defaulting to `T`. `$$storeMutators` is optional type metadata for the output list; neither wrapper needs to assign it at runtime.

Do not erase the lists to `[]` in your middleware's public signature: composition relies on preserving the other wrappers' API changes. Use module augmentation only when your wrapper actually changes the store API. A logger that only intercepts updates keeps the lists unchanged.

## Choose an existing extension

Before publishing your own wrapper, compare its purpose with the authors' [third-party library directory](https://zustand.docs.pmnd.rs/reference/integrations/third-party-libraries). It lists community extensions for tasks such as undo/redo, synchronization, and derived stores. These are community packages, not official recommendations from the Zustand maintainers; evaluate their maintenance and compatibility before adopting them.

For a running example of the React store-and-action pattern, explore the [live Zustand demo](https://zustand-demo.pmnd.rs/). The typed wrappers above extend that pattern with update interception and a store API property.

## Related

- [Type stores and selectors](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/type-stores-and-selectors) covers state inference and replacement typing.
- [Debug store actions](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/debug-store-actions) covers the shipped DevTools integration.
- [Update state with Immer](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/update-state-with-immer) covers the shipped draft-update middleware.
