Cookie Adapter
A cookie adapter stores data in browser cookies. This is useful when you need:
- Cross-subdomain sharing — Data accessible across
app.example.comandapi.example.com - Server access — Data sent with HTTP requests
- Legacy compatibility — Works with older systems expecting cookies
Live Demo
Implementation
Cookie adapters are not included in the library — you need to implement your own. We recommend using js-cookie for cookie handling.
See the demo source code above for a complete implementation example.
Usage
Once you’ve created your own createCookieAdapter function:
import { createStorageStore } from "@vp-tw/nanostores-storage";import { createCookieAdapter } from "./cookie-adapter"; // Your implementation
// Basic usageconst cookieAdapter = createCookieAdapter();const store = createStorageStore(cookieAdapter, "user-token");
// Cross-subdomainconst sharedAdapter = createCookieAdapter({ domain: ".example.com", // Note the leading dot secure: true, sameSite: "lax",});Cross-Subdomain Example
Share authentication between app.example.com and api.example.com:
const authAdapter = createCookieAdapter({ domain: ".example.com", expires: 7, // 7 days secure: true, sameSite: "strict",});
export const authTokenStore = createStorageStore(authAdapter, "auth-token");
export function login(token: string) { authTokenStore.set(token);}
export function logout() { authTokenStore.remove();}Fallback Chain with Cookies
Use localStorage with cookie backup for cross-subdomain sync:
import { createStorageStore, localStorageAdapter } from "@vp-tw/nanostores-storage";import { createCookieAdapter } from "./cookie-adapter";
const store = createStorageStore( [localStorageAdapter, createCookieAdapter({ domain: ".example.com" })], "user-preferences",);
// Reads from localStorage first (faster)// Writes to both (redundancy + cross-subdomain)Security Considerations
- Never store sensitive data in cookies without encryption
- Use
secure: truein production (HTTPS only) - Use
sameSite: "strict"for sensitive operations - Set appropriate expiration — don’t keep data forever
See Also
- Custom Adapters — How to build adapters
- Memory Adapter — Testing adapter
- Query String Adapter — URL query string example
- Fallback Chains — Combine adapters