Universal Cookie Management

8.1.0 · active · verified Sun Apr 19

universal-cookie is a JavaScript library designed for isomorphic cookie management across diverse environments, including client-side browsers, Node.js servers, and integrated within React applications (often via the `react-cookie` wrapper). It provides a consistent API for setting, getting, and removing HTTP cookies, abstracting away the underlying environment specifics. The current stable version is `8.1.0`, with the project maintaining an active release cadence, regularly providing minor and patch updates, and recently introducing major version `8.0.0`. Its core value proposition lies in enabling developers to write single-codebase solutions for cookie handling, simplifying full-stack development by offering a unified approach to cookie lifecycle management, supporting standard cookie attributes like `path`, `expires`, `domain`, `secure`, `httpOnly`, and `sameSite`.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates initializing the Cookies class, setting a JSON stringified cookie with options like expiration and path, and retrieving it. Includes type definitions for clarity.

import Cookies from 'universal-cookie';

interface MyCookieData {
  username: string;
  lastLogin: string;
}

const cookies = new Cookies();

// Set a cookie that expires in 1 hour
const expirationDate = new Date();
expirationDate.setTime(expirationDate.getTime() + 60 * 60 * 1000);

const userData: MyCookieData = {
  username: 'checklist_agent',
  lastLogin: new Date().toISOString()
};

cookies.set('user_session', JSON.stringify(userData), {
  path: '/',
  expires: expirationDate,
  secure: process.env.NODE_ENV === 'production',
  sameSite: 'lax' // Recommended for general use
});

console.log('Cookie set: user_session');

// Get a cookie
const storedSession = cookies.get('user_session');
if (storedSession) {
  const parsedData: MyCookieData = JSON.parse(storedSession);
  console.log('Retrieved user_session:', parsedData);
} else {
  console.log('user_session cookie not found.');
}

// Remove a cookie
// cookies.remove('user_session', { path: '/' });
// console.log('Cookie removed: user_session');

view raw JSON →