A simple package created to allow persisting a zustand store to a cookie 🙂. The package will automatically apply an expiry for the cookie as far in the future as possible (you can override this if you want).
pnpm add zustand-persist-cookie-storage
pnpm add -D @types/js-cookie
- Import the package using
import CookieStorage from 'zustand-persist-cookie-storage'
. - Import
createJSONStorage
from zustand usingimport { createJSONStorage } from 'zustand/middleware'
. - Create your store normally.
- In the persist options, set
storage
tostorage: createJSONStorage(() => CookieStorage())
. - Pass any cookie options to
CookieStorage
.
Your code should look something like:
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import CookieStorage from 'zustand-persist-cookie-storage';
export const usePersistedZustandStore = create(
persist(
...,
{
name: ...,
storage: createJSONStorage(() => CookieStorage({...[COOKIE OPTIONS GO HERE]}))
}
)
);
The type of cookie options should match CookieAttributes
from @types/js-cookie
(see @types/js-cookie for more info).