Universal cookies for React that work seamlessly across client-side and server-side rendering environments
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Direct cookie management through the Cookies class for advanced use cases, server-side integration, and direct cookie manipulation without React components.
Core cookie management class that provides direct access to cookie operations. This is the same class used internally by useCookies and withCookies.
/**
* Cookie management class for direct cookie operations
* Re-exported from universal-cookie package
*/
class Cookies {
constructor(cookies?: string | object, defaultSetOptions?: CookieSetOptions);
/** Get a single cookie value by name */
get(name: string, options?: CookieGetOptions): any;
/** Get a single cookie value by name with type safety */
get<T>(name: string, options?: CookieGetOptions): T;
/** Get all cookies as an object */
getAll(options?: CookieGetOptions): any;
/** Get all cookies as an object with type safety */
getAll<T>(options?: CookieGetOptions): T;
/** Set a cookie value with optional configuration */
set(name: string, value: any, options?: CookieSetOptions): void;
/** Remove a cookie by name */
remove(name: string, options?: CookieSetOptions): void;
/** Add listener for cookie changes */
addChangeListener(callback: CookieChangeListener): void;
/** Remove cookie change listener */
removeChangeListener(callback: CookieChangeListener): void;
/** Remove all cookie change listeners */
removeAllChangeListeners(): void;
/** Manually refresh cookies from browser storage */
update(): void;
}Usage Examples:
import { Cookies } from 'react-cookie';
// Client-side usage
const cookies = new Cookies();
// Server-side usage with cookie header
const serverCookies = new Cookies('user=john; theme=dark; session=abc123');
// With default options
const cookiesWithDefaults = new Cookies(undefined, {
path: '/',
secure: true,
sameSite: 'strict'
});Retrieve a single cookie value by name with optional parsing control.
/**
* Get a single cookie value by name
* @param name - Cookie name to retrieve
* @param options - Options controlling how the cookie is retrieved/parsed
* @returns Cookie value (parsed as object if JSON, or raw string)
*/
get(name: string, options?: CookieGetOptions): any;
interface CookieGetOptions {
/** Do not parse cookie value as JSON, return raw string */
doNotParse?: boolean;
/** Do not update cookies when accessing (internal use) */
doNotUpdate?: boolean;
}Usage Examples:
const cookies = new Cookies();
// Basic usage - automatically parses JSON
cookies.set('user', { name: 'John', role: 'admin' });
const user = cookies.get('user'); // Returns: { name: 'John', role: 'admin' }
// Get raw string value
const rawUser = cookies.get('user', { doNotParse: true }); // Returns: '{"name":"John","role":"admin"}'
// Get non-existent cookie
const missing = cookies.get('nonexistent'); // Returns: undefined
// Get simple string cookie
cookies.set('theme', 'dark');
const theme = cookies.get('theme'); // Returns: 'dark'Retrieve all cookies as a key-value object.
/**
* Get all cookies as an object
* @param options - Options controlling how cookies are retrieved/parsed
* @returns Object with cookie names as keys and values as values
*/
getAll(options?: CookieGetOptions): { [name: string]: any };Usage Examples:
const cookies = new Cookies();
// Set multiple cookies
cookies.set('username', 'john');
cookies.set('preferences', { theme: 'dark', lang: 'en' });
cookies.set('session', 'abc123');
// Get all cookies (with JSON parsing)
const allCookies = cookies.getAll();
// Returns:
// {
// username: 'john',
// preferences: { theme: 'dark', lang: 'en' },
// session: 'abc123'
// }
// Get all cookies as raw strings
const rawCookies = cookies.getAll({ doNotParse: true });
// Returns:
// {
// username: 'john',
// preferences: '{"theme":"dark","lang":"en"}',
// session: 'abc123'
// }Set a cookie value with comprehensive configuration options.
/**
* Set a cookie value with optional configuration
* @param name - Cookie name
* @param value - Cookie value (automatically JSON-stringified if object)
* @param options - Cookie configuration options
*/
set(name: string, value: any, options?: CookieSetOptions): void;
interface CookieSetOptions {
/** Cookie path (default: current path) */
path?: string;
/** Absolute expiration date */
expires?: Date;
/** Max age in seconds from when client receives it */
maxAge?: number;
/** Cookie domain (sub.domain.com or .allsubdomains.com) */
domain?: string;
/** HTTPS only flag */
secure?: boolean;
/** Server access only flag (cannot be read by JavaScript) */
httpOnly?: boolean;
/** SameSite policy for CSRF protection */
sameSite?: boolean | 'none' | 'lax' | 'strict';
/** Partitioned storage flag for third-party contexts */
partitioned?: boolean;
}Usage Examples:
const cookies = new Cookies();
// Basic usage
cookies.set('username', 'john');
// With expiration (24 hours from now)
cookies.set('session', 'abc123', {
expires: new Date(Date.now() + 24 * 60 * 60 * 1000)
});
// With max age (1 hour in seconds)
cookies.set('temporary', 'data', {
maxAge: 3600
});
// Complex object value (automatically JSON-stringified)
cookies.set('user_preferences', {
theme: 'dark',
language: 'en',
notifications: true
});
// Security-focused cookie
cookies.set('auth_token', 'secret', {
path: '/',
secure: true, // HTTPS only
httpOnly: true, // No JavaScript access
sameSite: 'strict' // CSRF protection
});
// Domain-specific cookie
cookies.set('global_setting', 'value', {
domain: '.example.com', // Available on all subdomains
path: '/',
maxAge: 86400 // 24 hours
});
// Third-party context cookie
cookies.set('tracking', 'id123', {
sameSite: 'none',
secure: true,
partitioned: true
});Remove a cookie by name, requiring matching path and domain options.
/**
* Remove a cookie by name
* @param name - Cookie name to remove
* @param options - Must match path/domain used when setting the cookie
*/
remove(name: string, options?: CookieSetOptions): void;Usage Examples:
const cookies = new Cookies();
// Basic removal
cookies.remove('username');
// Remove cookie with specific path (must match original path)
cookies.set('data', 'value', { path: '/admin' });
cookies.remove('data', { path: '/admin' }); // Correct
cookies.remove('data'); // Won't work - path mismatch
// Remove domain-specific cookie
cookies.set('global', 'value', { domain: '.example.com', path: '/' });
cookies.remove('global', { domain: '.example.com', path: '/' });
// Remove secure cookie
cookies.set('secure_data', 'value', { secure: true, path: '/' });
cookies.remove('secure_data', { path: '/' }); // secure flag not needed for removalAdd and remove listeners for cookie changes, useful for reactive applications.
/**
* Add listener for cookie changes
* @param callback - Function called when any cookie changes with change details
*/
addChangeListener(callback: CookieChangeListener): void;
/**
* Remove cookie change listener
* @param callback - Previously added callback function
*/
removeChangeListener(callback: CookieChangeListener): void;
/**
* Remove all cookie change listeners
*/
removeAllChangeListeners(): void;Usage Examples:
const cookies = new Cookies();
// Create listener function with change details
const handleCookieChange = (change: CookieChangeOptions) => {
console.log(`Cookie '${change.name}' changed to:`, change.value);
if (change.options) {
console.log('Options:', change.options);
}
};
// Add listener
cookies.addChangeListener(handleCookieChange);
// Make changes - listener will be called with details
cookies.set('test', 'value'); // Triggers handleCookieChange with {name: 'test', value: 'value', options: {...}}
cookies.remove('test'); // Triggers handleCookieChange with {name: 'test', value: undefined, options: {...}}
// Remove listener when done
cookies.removeChangeListener(handleCookieChange);
// Multiple listeners example
const listener1 = (change: CookieChangeOptions) => console.log('Listener 1:', change.name);
const listener2 = (change: CookieChangeOptions) => console.log('Listener 2:', change.name);
cookies.addChangeListener(listener1);
cookies.addChangeListener(listener2);
cookies.set('trigger', 'both'); // Both listeners called
// Clean up individual listeners
cookies.removeChangeListener(listener1);
cookies.removeChangeListener(listener2);
// Or clean up all listeners at once
// cookies.removeAllChangeListeners();Manually refresh cookies from browser storage, typically not needed as changes are automatically detected.
/**
* Manually refresh cookies from browser storage
* Usually not needed as cookie changes are automatically detected
*/
update(): void;Usage Examples:
const cookies = new Cookies();
// Force refresh from browser (rarely needed)
cookies.update();
// Use case: External script modified document.cookie
document.cookie = 'external=value; path=/';
cookies.update(); // Ensure cookies instance sees the change
console.log(cookies.get('external')); // Now returns 'value'Direct usage in server environments with cookie headers.
import { Cookies } from 'react-cookie';
import { Request, Response } from 'express';
// Express middleware example
function cookieMiddleware(req: Request, res: Response, next: Function) {
// Parse cookies from request header
const cookies = new Cookies(req.headers.cookie);
// Access cookies
const userId = cookies.get('user_id');
const sessionToken = cookies.get('session');
// Set response cookies
const responseCookies = new Cookies();
responseCookies.set('last_visit', new Date().toISOString());
// Add to response headers
const cookieHeader = responseCookies.getAll();
Object.entries(cookieHeader).forEach(([name, value]) => {
res.cookie(name, value);
});
next();
}
// Next.js API route example
export default function handler(req: NextApiRequest, res: NextApiResponse) {
const cookies = new Cookies(req.headers.cookie);
const userPrefs = cookies.get('preferences');
// Process request based on cookie data
if (userPrefs?.theme === 'dark') {
// Handle dark theme logic
}
res.json({ message: 'Success' });
}interface CookieChangeOptions {
name: string;
value?: any;
options?: CookieSetOptions;
}
type CookieChangeListener = (options: CookieChangeOptions) => void;Install with Tessl CLI
npx tessl i tessl/npm-react-cookie