cookie vs js-cookie vs universal-cookie vs react-cookie
Handling HTTP Cookies in JavaScript Applications
cookiejs-cookieuniversal-cookiereact-cookie

Handling HTTP Cookies in JavaScript Applications

cookie is a low-level HTTP cookie parser and serializer designed for Node.js servers. js-cookie provides a simple API for managing cookies exclusively in the browser environment. react-cookie offers React hooks to manage cookie state within functional components. universal-cookie enables isomorphic cookie handling that works on both the server and client sides.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
cookie139,346,8571,53660.8 kB144 months agoMIT
js-cookie17,791,70722,57025.9 kB85 months agoMIT
universal-cookie1,140,19821563.7 kB66 months agoMIT
react-cookie527,45721571.7 kB66 months agoMIT

Cookie Libraries: Client, Server, and React Compared

Managing HTTP cookies is a common requirement in web development, but the right tool depends heavily on where your code runs. The cookie, js-cookie, react-cookie, and universal-cookie packages each solve this problem differently based on environment and framework needs. Let's compare how they handle common tasks.

🌍 Environment Support: Browser vs Node vs Universal

cookie works only in Node.js or server environments.

  • It parses incoming Cookie headers and serializes Set-Cookie headers.
  • It cannot access document.cookie in the browser.
// cookie: Server-side parsing
const cookie = require('cookie');
const parsed = cookie.parse(req.headers.cookie);
const serialized = cookie.serialize('session', 'abc123', { httpOnly: true });

js-cookie works only in the browser.

  • It wraps document.cookie with a safer API.
  • It will throw an error if used in a Node.js environment without polyfills.
// js-cookie: Browser-only
import Cookies from 'js-cookie';
Cookies.set('session', 'abc123', { expires: 7 });
const value = Cookies.get('session');

react-cookie is designed for React clients.

  • It runs in the browser but relies on React context.
  • Server support requires additional setup with universal-cookie.
// react-cookie: React Client
import { useCookies } from 'react-cookie';
const [cookies, setCookie] = useCookies(['session']);
setCookie('session', 'abc123', { path: '/' });

universal-cookie works everywhere.

  • It detects the environment and uses headers or document.cookie automatically.
  • Ideal for code that runs during SSR and hydration.
// universal-cookie: Isomorphic
import Cookies from 'universal-cookie';
const cookies = new Cookies();
cookies.set('session', 'abc123', { path: '/' });
const value = cookies.get('session');

πŸ“ API Style: Functions vs Classes vs Hooks

cookie uses static functions for parsing and serializing.

  • You pass strings in and get strings or objects out.
  • No state is maintained between calls.
// cookie: Static functions
const obj = cookie.parse('foo=bar; baz=qux');
const str = cookie.serialize('foo', 'bar', { maxAge: 3600 });

js-cookie uses a static object with methods.

  • You call methods directly on the Cookies object.
  • Simple and global, no instantiation needed.
// js-cookie: Static object
Cookies.set('name', 'value');
Cookies.remove('name');

react-cookie uses React hooks.

  • You call hooks inside components to get setters and getters.
  • Returns an array similar to useState.
// react-cookie: Hooks
const [cookies, setCookie, removeCookie] = useCookies(['name']);

universal-cookie uses a class instance.

  • You must create a new Cookies object first.
  • Methods are called on that instance.
// universal-cookie: Class instance
const cookies = new Cookies();
cookies.set('name', 'value');
cookies.remove('name');

βš›οΈ React Integration: Hooks vs Manual State

cookie has no React integration.

  • You must manually manage state if you want UI updates.
  • Best used inside API routes or middleware.
// cookie: No React support
// Must manually update state after parsing
const [session, setSession] = useState(null);
// useEffect to parse using cookie library

js-cookie has no React integration.

  • You must wrap calls in useEffect to avoid SSR mismatches.
  • Does not trigger re-renders when cookies change.
// js-cookie: Manual React usage
useEffect(() => {
  const val = Cookies.get('session');
  setSession(val);
}, []);

react-cookie is built for React.

  • Components re-render automatically when cookies change.
  • Handles subscription logic internally.
// react-cookie: Auto re-render
function Profile() {
  const [cookies] = useCookies(['userId']);
  return <div>{cookies.userId}</div>; // Updates automatically
}

universal-cookie has limited React integration.

  • It provides a CookieProvider but hooks are in react-cookie.
  • Often used as the engine behind react-cookie.
// universal-cookie: With Provider
import { CookieProvider } from 'react-cookie';
// universal-cookie handles the logic underneath

πŸ›‘οΈ SSR Compatibility: Headers vs Document

cookie is native to SSR.

  • It works directly with HTTP headers in Node.js.
  • No browser APIs are involved.
// cookie: SSR Native
export async function loader({ request }) {
  const cookies = cookie.parse(request.headers.get('Cookie'));
  return json({ user: cookies.user });
}

js-cookie is not compatible with SSR.

  • It relies on document which is undefined on the server.
  • Using it in SSR will crash the build.
// js-cookie: SSR Unsafe
// Do not use in server code
// Will throw ReferenceError: document is not defined

react-cookie supports SSR with configuration.

  • It needs universal-cookie to read headers on the server.
  • Requires wrapping the app in a provider during render.
// react-cookie: SSR Setup
import { CookiesProvider } from 'react-cookie';
// Wrap app in SSR render to pass initial cookies

universal-cookie is designed for SSR.

  • It accepts an initial cookie string from the server.
  • Seamlessly switches to browser API after hydration.
// universal-cookie: SSR Ready
const cookies = new Cookies(req.headers.cookie);
// Works on server, then switches to document.cookie on client

πŸ“Š Summary: Key Differences

Featurecookiejs-cookiereact-cookieuniversal-cookie
EnvironmentπŸ–₯️ Node.js Only🌐 Browser Onlyβš›οΈ React Client🌍 Universal (SSR + Client)
API StyleπŸ”§ Static FunctionsπŸ“¦ Static Object🎣 React HooksπŸ—οΈ Class Instance
Reactivity❌ None❌ Noneβœ… Auto Re-render⚠️ Via react-cookie
SSR Readyβœ… Native❌ Crashes⚠️ Needs Setupβœ… Native
DependenciesπŸƒ NoneπŸƒ Noneβš›οΈ React + universal-cookieπŸƒ None

πŸ’‘ Final Recommendation

cookie is the foundation for backend developers πŸ–₯️ β€” use it when you need to parse headers in Express or Node.js servers without extra dependencies.

js-cookie is the standard for simple browser scripts 🌐 β€” pick it for legacy jQuery projects or simple sites that never render on the server.

react-cookie is the choice for modern React apps βš›οΈ β€” select it when you need cookies to drive UI state and trigger component updates automatically.

universal-cookie is the engine for isomorphic apps 🌍 β€” rely on it when you are building with Next.js or custom SSR and need one API for both server and client.

Final Thought: Despite their differences, all four packages aim to simplify cookie management. Choose based on where your code runs β€” server, browser, or both β€” and whether you need React reactivity.

How to Choose: cookie vs js-cookie vs universal-cookie vs react-cookie

  • cookie:

    Choose cookie if you are building Node.js server middleware or need to parse raw HTTP header strings manually. It is the standard for backend cookie handling and does not depend on browser APIs. This package is best for low-level control without any framework dependencies.

  • js-cookie:

    Choose js-cookie if you are working exclusively in the browser and want a simple API for setting and getting values. It handles encoding and expiration dates automatically without extra configuration. This tool is ideal for standard client-side projects that do not require server-side rendering.

  • universal-cookie:

    Choose universal-cookie if you need to access cookies during server-side rendering or in a Node.js environment alongside the browser. It abstracts the difference between HTTP headers and browser document access into a single class. This package is the right choice for isomorphic applications using Next.js or custom SSR setups.

  • react-cookie:

    Choose react-cookie if your application is built with React and you need to access cookies within functional components. It provides hooks that trigger re-renders when cookie values change, keeping UI in sync with state. Use this for client-heavy React apps where cookie reactivity is required.

README for cookie

cookie

NPM Version NPM Downloads Build Status Coverage Status

Basic HTTP cookie parser and serializer for HTTP servers.

Installation

$ npm install cookie

API

import * as cookie from "cookie";

cookie.parseCookie(str, options)

Parse an HTTP Cookie header string and return an object of all cookie name-value pairs. The str argument is the string representing a Cookie header value and options is an optional object containing additional parsing options.

const cookieObject = cookie.parseCookie("foo=bar; equation=E%3Dmc%5E2");
// { foo: 'bar', equation: 'E=mc^2' }

Options

cookie.stringifyCookie(cookieObj, options)

Stringifies a cookie object into an HTTP Cookie header.

const cookieHeader = cookie.stringifyCookie({ a: "foo", b: "bar" });
// a=foo; b=bar

Options

cookie.parseSetCookie(str, options)

Parse an HTTP Set-Cookie header string and return an object of the options.

const setCookieObject = cookie.parseSetCookie("foo=bar; httpOnly");
// { name: "foo", value: "bar", httpOnly: true }

Note: Cookie follows the specification and ignores invalid attributes, but does not attempt to normalize or modify any attributes as a browser might. For example:

cookie.parseSetCookie(
  "session=abc; max-age=1.5; expires=invalid; custom=value; domain=example.com",
);
// { name: "session", value: "abc", domain: "example.com" }

Options

cookie.stringifySetCookie(setCookieObj, options)

Stringifies a Set-Cookie object into a Set-Cookie header string.

const setCookieHeader = cookie.stringifySetCookie({
  name: "foo",
  value: "bar",
});
// foo=bar

Options

Cookie object

The cookie object represents all cookie name-value pairs in a Cookie header, where { name: "value" } is used for name=value.

Set-Cookie object

The Set-Cookie object represents all the options in a Set-Cookie header.

name

The name of the cookie.

value

The value of a cookie after it has been decoded.

maxAge

Specifies the number (in seconds) to be the value for the Max-Age Set-Cookie attribute.

The cookie storage model specification states that if both expires and maxAge are set, then maxAge takes precedence, but it is possible not all clients by obey this, so if both are set, they should point to the same date and time.

expires

Specifies the Date object to be the value for the Expires Set-Cookie attribute. When no expiration is set, clients consider this a "non-persistent cookie" and delete it when the current session is over.

The cookie storage model specification states that if both expires and maxAge are set, then maxAge takes precedence, but it is possible not all clients by obey this, so if both are set, they should point to the same date and time.

domain

Specifies the value for the Domain Set-Cookie attribute. When no domain is set, clients consider the cookie to apply to the current domain only.

path

Specifies the value for the Path Set-Cookie attribute. When no path is set, the path is considered the "default path".

httpOnly

Enables the HttpOnly Set-Cookie attribute. When enabled, clients will not allow client-side JavaScript to see the cookie in document.cookie.

secure

Enables the Secure Set-Cookie attribute. When enabled, clients will only send the cookie back if the browser has an HTTPS connection.

partitioned

Enables the Partitioned Set-Cookie attribute. When enabled, clients will only send the cookie back when the current domain and top-level domain matches.

This is an attribute that has not yet been fully standardized, and may change in the future. This also means clients may ignore this attribute until they understand it. More information about can be found in the proposal.

priority

Specifies the value for the Priority Set-Cookie attribute.

  • 'low' will set the Priority attribute to Low.
  • 'medium' will set the Priority attribute to Medium, the default priority when not set.
  • 'high' will set the Priority attribute to High.

More information about priority levels can be found in the specification.

sameSite

Specifies the value for the SameSite Set-Cookie attribute.

  • true will set the SameSite attribute to Strict for strict same site enforcement.
  • 'lax' will set the SameSite attribute to Lax for lax same site enforcement.
  • 'none' will set the SameSite attribute to None for an explicit cross-site cookie.
  • 'strict' will set the SameSite attribute to Strict for strict same site enforcement.

More information about enforcement levels can be found in the specification.

Encode and decode

Cookie accepts encode or decode options for processing a cookie-value. Since the value of a cookie has a limited character set (and must be a simple string), these functions are used to transform values into strings suitable for a cookies value.

The default encode function preserves roundtrip-safe cookie-octet values and uses the global encodeURIComponent otherwise.

The default decode function is the global decodeURIComponent, wrapped in a try..catch. If an error is thrown it will return the cookie's original value. If you provide your own encode/decode scheme you must ensure errors are appropriately handled. Custom decode functions can return undefined, which will skip the cookie during parse and try again with a future cookie of the same name.

Example

The following example uses this module in conjunction with the Node.js core HTTP server to prompt a user for their name and display it back on future visits.

var cookie = require("cookie");
var escapeHtml = require("escape-html");
var http = require("http");
var url = require("url");

function onRequest(req, res) {
  // Parse the query string
  var query = url.parse(req.url, true, true).query;

  if (query && query.name) {
    // Set a new cookie with the name
    res.setHeader(
      "Set-Cookie",
      cookie.stringifySetCookie({
        name: "name",
        value: String(query.name),
        httpOnly: true,
        maxAge: 60 * 60 * 24 * 7, // 1 week
      }),
    );

    // Redirect back after setting cookie
    res.statusCode = 302;
    res.setHeader("Location", req.headers.referer || "/");
    res.end();
    return;
  }

  // Parse the cookies on the request
  var cookies = cookie.parseCookie(req.headers.cookie || "");

  // Get the visitor name set in the cookie
  var name = cookies.name;

  res.setHeader("Content-Type", "text/html; charset=UTF-8");

  if (name) {
    res.write("<p>Welcome back, <b>" + escapeHtml(name) + "</b>!</p>");
  } else {
    res.write("<p>Hello, new visitor!</p>");
  }

  res.write('<form method="GET">');
  res.write(
    '<input placeholder="enter your name" name="name"> <input type="submit" value="Set Name">',
  );
  res.end("</form>");
}

http.createServer(onRequest).listen(3000);

Testing

npm test

Benchmark

npm run bench
     name                   hz     min     max    mean     p75     p99    p995    p999     rme  samples
   Β· simple       8,566,313.09  0.0000  0.3694  0.0001  0.0001  0.0002  0.0002  0.0003  Β±0.64%  4283157   fastest
   Β· decode       3,834,348.85  0.0001  0.2465  0.0003  0.0003  0.0003  0.0004  0.0006  Β±0.38%  1917175
   Β· unquote      8,315,355.96  0.0000  0.3824  0.0001  0.0001  0.0002  0.0002  0.0003  Β±0.72%  4157880
   Β· duplicates   1,944,765.97  0.0004  0.2959  0.0005  0.0005  0.0006  0.0006  0.0008  Β±0.24%   972384
   Β· 10 cookies     675,345.67  0.0012  0.4328  0.0015  0.0015  0.0019  0.0020  0.0058  Β±0.75%   337673
   Β· 100 cookies     61,040.71  0.0152  0.4092  0.0164  0.0160  0.0196  0.0228  0.2260  Β±0.71%    30521   slowest
   βœ“ parse top-sites (15) 22945ms
     name                                  hz     min     max    mean     p75     p99    p995    p999     rme   samples
   Β· parse accounts.google.com   7,164,349.17  0.0000  0.0929  0.0001  0.0002  0.0002  0.0002  0.0003  Β±0.09%   3582184
   Β· parse apple.com             7,817,686.84  0.0000  0.6048  0.0001  0.0001  0.0002  0.0002  0.0003  Β±1.05%   3908844
   Β· parse cloudflare.com        7,189,841.70  0.0000  0.0390  0.0001  0.0002  0.0002  0.0002  0.0003  Β±0.06%   3594921
   Β· parse docs.google.com       7,051,765.61  0.0000  0.0296  0.0001  0.0002  0.0002  0.0002  0.0003  Β±0.06%   3525883
   Β· parse drive.google.com      7,349,104.77  0.0000  0.0368  0.0001  0.0001  0.0002  0.0002  0.0003  Β±0.05%   3674553
   Β· parse en.wikipedia.org      1,929,909.49  0.0004  0.3598  0.0005  0.0005  0.0007  0.0007  0.0012  Β±0.16%    964955
   Β· parse linkedin.com          2,225,658.01  0.0003  0.0595  0.0004  0.0005  0.0005  0.0005  0.0006  Β±0.06%   1112830
   Β· parse maps.google.com       4,423,511.68  0.0001  0.0942  0.0002  0.0003  0.0003  0.0003  0.0005  Β±0.08%   2211756
   Β· parse microsoft.com         3,387,601.88  0.0002  0.0725  0.0003  0.0003  0.0004  0.0004  0.0005  Β±0.09%   1693801
   Β· parse play.google.com       7,375,980.86  0.0000  0.1994  0.0001  0.0001  0.0002  0.0002  0.0003  Β±0.12%   3687991
   Β· parse support.google.com    4,912,267.94  0.0001  2.8958  0.0002  0.0002  0.0003  0.0003  0.0005  Β±1.28%   2456134
   Β· parse www.google.com        3,443,035.87  0.0002  0.2783  0.0003  0.0003  0.0004  0.0004  0.0007  Β±0.51%   1721518
   Β· parse youtu.be              1,910,492.87  0.0004  0.3490  0.0005  0.0005  0.0007  0.0007  0.0011  Β±0.46%    955247
   Β· parse youtube.com           1,895,082.62  0.0004  0.7454  0.0005  0.0005  0.0006  0.0007  0.0013  Β±0.64%    947542   slowest
   Β· parse example.com          21,582,835.27  0.0000  0.1095  0.0000  0.0000  0.0001  0.0001  0.0001  Β±0.13%  10791418

References

License

MIT