zustand-jscookie-storage
v1.0.0
Published
🐻 + 🍪 Zustand plugin to persist state to cookies the battle-tested js-cookie library. Perfect to share state between Server-Side and Client-Side.
Maintainers
Readme
Zustand JS Cookie Storage 🐻 🍪
A Zustand plugin to persist state to cookies using the battle-tested js-cookie library. Perfect for sharing state between Server-Side and Client-Side applications.
Installation
npm install js-cookie zustand-jscookie-storage
# or
yarn add js-cookie zustand-jscookie-storage
# or
pnpm add js-cookie zustand-jscookie-storageUsage
Basic Setup
Create a Zustand store with cookie persistence:
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
// Import the lib
import { CookieStorage } from "zustand-jscookie-storage";
// Create cookie storage instance
const cookieStorage = new CookieStorage();
// Create your store with persistence
export const useCookieStore = create()(
persist(
(set) => ({
// Your state here
}),
{
name: "my-cookie-store", // Cookie name
storage: createJSONStorage(() => cookieStorage),
}
)
);Custom Cookie Attributes
You can customize cookie attributes like expiration, security settings, and more:
import { CookieStorage } from "zustand-jscookie-storage";
// Custom cookie attributes
const cookieStorage = new CookieStorage({
expires: 7, // 7 days
secure: true,
sameSite: "strict",
path: "/",
domain: ".example.com",
});Default Cookie Attributes
If no attributes are provided, the following secure defaults are used:
expires: 30 dayshttpOnly: false (required for client-side access)path: '/'sameSite: 'strict'secure: true
To see the list of all attributes refer to js-cookie docs
Alternatives
License
MIT
