What Happens When You Use Zustand in Next.js Like You Do in React

The Start of a Terrifying Bug

async function getAccessTokenWithFallback(): Promise<string | null> {
  const accessTokenByMemory = useCommonStore.getState().accessToken;

  if (accessTokenByMemory) {
    return accessTokenByMemory;
  }

  try {
    const accessTokenByCookie = await getAccessToken();
    return accessTokenByCookie || null;
  } catch (error) {
    console.error('[AuthBridge] ❌ Failed to retrieve token', error);
    return null;
  }
}

During a recent code review, I came across logic managing an access token. Reading it directly with getState from a utility function usable on both client and server, rather than a client component, felt unfamiliar, so I remember taking a closer look. But the fallback seemed safely handled, and I assumed it would work correctly on both sides. Shortly afterward, however, this code caused a frightening bug in production on Next.js: user A logged in, and A’s account information appeared on user B’s screen.


Let’s Find Out Why This Happened

Q. Why was it fine in React?

In React (SPA), the Zustand store exists as a singleton in browser memory.

One browser tab = one JavaScript runtime = one Zustand store instance

When user A logs in, A’s token is saved in the store. That store exists only inside A’s browser tab. User B opens the app in their own browser, with their own JavaScript runtime and Zustand store. The two stores occupy physically separate memory spaces, so they never get mixed up.

Why does each browser tab have an independent runtime?

The browser runs a separate JavaScript engine for each tab. One tab can’t access another tab’s memory. This is a fundamental part of its security model. Thanks to this, no matter how loosely global state is managed in a React SPA, it fundamentally can’t mix with another user’s state.


Q. Why is the Next.js server environment different?

A server (Node.js) differs from a browser. One process handles requests from every user.

User A request ─┐
User B request ─┤─▶ One Node.js process ─▶ One shared memory space
User C request ─┘

Each user doesn’t get an independent runtime. The server handles thousands of concurrent requests in a single process.

Why not create a new process for each request?

Creating a process is expensive. Allocating memory, loading code, and initializing it all take time. A server couldn’t cope with repeating that for every incoming request. Instead, it keeps one process running and handles requests asynchronously. This is efficient, but comes with the side effect of shared memory.


Q. How does a Zustand store exist on the server, then?

A Zustand store created with create() executes exactly once in the top-level scope of a JavaScript module.

// common.store.ts
const useCommonStore = create<CommonState>()((set) => ({
  accessToken: null,
  // ...
}));

export default useCommonStore; // The store is created at this point

The store is created the first time this file is imported. Every later import, from anywhere, returns the same instance. That’s how the JavaScript module system works.

Why isn’t a module executed again every time it’s imported?

Node.js caches loaded modules. If you import the same module path twice, the second import onward returns the cached result. This is another design choice for performance. As a result, top-level module code runs exactly once during the server’s entire lifetime.

The lifetime of a server-side Zustand store therefore looks like this.

Server starts → Store created (once) → Same instance until the server shuts down
                                       ↑
                          Millions of requests share the same store during this time

Q. How exactly do the tokens get mixed up?

Consider this scenario.

T=0ms  User A logs in → Server saves A's token in the Zustand store
         useCommonStore.setState({ accessToken: 'token_A' })

T=1ms  User B requests a page → Server runs getAccessTokenWithFallback()
         useCommonStore.getState().accessToken
         → Returns 'token_A' ← B's request retrieves A's token

T=1ms  B's request calls the API with A's token
         → A's profile and data appear on B's screen

Node.js is single-threaded, but handles I/O asynchronously. It’s perfectly normal for B’s request to come in while A’s is being processed. If the store is holding A’s state in between, B reads it as-is.

Why is this bug hard to see in local development? When testing alone locally, request timing doesn’t overlap. It only comes to light in a production environment with high traffic.


Let’s recap what caused the problem.

  1. Server code reads or writes a Zustand store made with create().
  2. Two users’ requests overlap in time (which can happen constantly in production).
  3. The store holds values that should differ per request, such as tokens, sessions, or user information.

When all three conditions are met, this bug is bound to happen.


What Zustand Recommends for Next.js

Zustand’s official documentation specifies using createStore() + the Provider pattern instead of create() in Next.js.

Next.js Setup Guide SSR and Hydration Guide

Why recommend createStore + Provider?

Ultimately, the problem was that the store was a module-level singleton. The solution, then, is to avoid making the store a singleton.

Specifically, we need two things.

  1. Create a fresh store every time the function is called (createStore + factory pattern).
  2. Pass the store through React Context, so each render tree has its own store.

Q. What’s the difference between create() and createStore()?

// create() — create and return the store immediately
const useStore = create<State>()((set) => ({ ... }));
// The store is created here, when the module loads.

// createStore() — return a function that creates a store
const createMyStore = () => createStore<State>()((set) => ({ ... }));
// Nothing is created yet. The store is created only when the function is called.

create() creates the store when it’s declared. createStore() defines only the blueprint. The actual store is created later through an explicit call.

Why does this difference matter?

Calling the factory function createMyStore() for each request creates a completely new store instance each time. Instead of a singleton created once at server startup, we get a store with a lifetime matching the request.

Step 1: Define a factory function with createStore

// stores/auth.store.ts
import { createStore } from 'zustand';

interface AuthState {
  accessToken: string | null;
  setAccessToken: (token: string | null) => void;
}

// Use createStore() instead of create() to avoid creating a singleton
export const createAuthStore = (initialToken: string | null = null) =>
  createStore<AuthState>()((set) => ({
    accessToken: initialToken,
    setAccessToken: (token) => set({ accessToken: token }),
  }));

export type AuthStore = ReturnType<typeof createAuthStore>;

Q. Is defining a factory with createStore enough?

No. Defining a factory doesn’t automatically create a store for every request. Something needs to call it at the right time and pass the resulting store into the component tree. That’s the Provider’s role.

Step 2: A Provider that creates a fresh store per request

// providers/auth-store-provider.tsx
'use client';

import { createContext, useContext, useRef, type ReactNode } from 'react';
import { useStore } from 'zustand';
import { createAuthStore, type AuthStore } from '@/stores/auth.store';

const AuthStoreContext = createContext<AuthStore | null>(null);

interface AuthStoreProviderProps {
  children: ReactNode;
  initialToken?: string | null;
}

export function AuthStoreProvider({ children, initialToken }: AuthStoreProviderProps) {
  // Use useRef to avoid recreating it on every render
  const storeRef = useRef<AuthStore | null>(null);

  if (!storeRef.current) {
    storeRef.current = createAuthStore(initialToken);
  }

  return (
    <AuthStoreContext.Provider value={storeRef.current}>
      {children}
    </AuthStoreContext.Provider>
  );
}

export function useAuthStore<T>(selector: (state: ReturnType<AuthStore['getState']>) => T): T {
  const store = useContext(AuthStoreContext);
  if (!store) throw new Error('Must be used within AuthStoreProvider');
  return useStore(store, selector);
}

Q. Why does the Provider need useRef?

const storeRef = useRef<AuthStore | null>(null);

if (!storeRef.current) {
  storeRef.current = createAuthStore(initialToken);
}

Simply calling createAuthStore() without useRef would create a new store on every render. Whenever the parent rerenders, the Provider rerenders too. Resetting the store each time would wipe out all its state.

useRef keeps the same value from mount until unmount. Even after rerenders, storeRef.current still points to the original store. This means the store is created exactly once on the client and then reused.

Q. How can we inject an initial value from the server?

If each request creates a fresh store, how do we put the token retrieved on the server into it? This is where initialToken comes in. The server component (layout.tsx) reads the cookie and passes it to the Provider as a prop, and the Provider initializes the store with that value.

Step 3: Inject the initial value from the server and wrap with the Provider

// app/layout.tsx
import { cookies } from 'next/headers';
import { AuthStoreProvider } from '@/providers/auth-store-provider';

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  // Read the token on the server for each request and pass it to the Provider
  const cookieStore = cookies();
  const initialToken = cookieStore.get('access_token')?.value ?? null;

  return (
    <html>
      <body>
        <AuthStoreProvider initialToken={initialToken}>
          {children}
        </AuthStoreProvider>
      </body>
    </html>
  );
}

Q. Why read cookies in layout.tsx? Aren’t cookies shared too?

Next.js’s cookies() reads cookies from the current request’s HTTP headers. Each request has different headers, so its cookies differ too. This is data carried in each HTTP request, rather than global state stored in server memory like the Zustand store.

User A's request → Cookie: access_token=token_A → cookies() reads token_A
User B's request → Cookie: access_token=token_B → cookies() reads token_B

There’s no reason for the requests to get mixed up: each brings its own cookies.

Q. Should server functions always read tokens from cookies, then?

Yes. The rule is to avoid touching the Zustand store in the server environment. If code running on the server—a Server Component, Server Action, or Route Handler—needs a token, always read it directly from cookies() or headers().

Why can’t we even read the store on the server?

Reading alone is dangerous, because values saved during a previous request may remain. Any code accessing the store on the server is a potential bug.

Step 4: Read the token directly from cookies in server actions

// Don't access the store in the server environment
async function getAccessTokenWithFallback(): Promise<string | null> {
  // Server: read directly from cookies
  if (typeof window === 'undefined') {
    const { cookies } = await import('next/headers');
    const cookieStore = cookies();
    return cookieStore.get('access_token')?.value ?? null;
  }

  // Client: store or cookie fallback
  try {
    const accessTokenByCookie = await getAccessToken();
    return accessTokenByCookie || null;
  } catch (error) {
    console.error('[AuthBridge] ❌ Failed to retrieve token', error);
    return null;
  }
}

Q. Does the Provider pattern avoid hydration problems?

Hydration connects server-rendered HTML to a React tree on the client. If the server and client initial states differ, it causes a hydration mismatch.

Injecting initialToken into the Provider naturally resolves this.

Server: cookies() reads token_A → Pass initialToken=token_A to Provider → Render HTML
Client: Receive server HTML → Mount the same Provider, initialized with initialToken=token_A
→ Server and client initial states match → Hydration succeeds

Why is a mismatch between initial values a problem?

During hydration, React reuses server-rendered HTML and attaches event handlers to it. If a different initial state on the client produces different HTML, the existing DOM differs from the DOM React expects, causing a mismatch. In the worst case, the whole tree rerenders or the screen flickers.


Recap

React (SPA)Next.js (SSR)
Runtime environmentOne browserOne server (shared by N users)
Zustand store lifetimeWhile the tab is openWhile the server is running
Using create()SafeDangerous—state shared across requests
createStore() + ProviderUnnecessaryRequired
Reading tokens on the serverStore is OKDirectly from cookies/headers