cookie vs js-cookie vs universal-cookie
Cookie Management Strategies in JavaScript Applications
cookiejs-cookieuniversal-cookieSimilar Packages:

Cookie Management Strategies in JavaScript Applications

cookie is a low-level Node.js utility for parsing and serializing cookie strings without direct browser or server interaction. js-cookie is a lightweight browser-focused library that simplifies document.cookie access with a clean API. universal-cookie provides an isomorphic solution for React applications, enabling cookie management across server-side rendering (SSR) and client-side environments.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
cookie01,47560.5 kB134 months agoMIT
js-cookie022,78026.2 kB33 years agoMIT
universal-cookie021365.6 kB32 days agoMIT

Cookie Management Strategies: cookie vs js-cookie vs universal-cookie

Managing HTTP cookies in JavaScript varies significantly depending on whether you are working on the server, the browser, or both. The cookie, js-cookie, and universal-cookie packages each solve this problem with different levels of abstraction and environment support. Let's compare how they handle common engineering tasks.

🌍 Environment Support: Server vs Client vs Both

cookie is designed for Node.js servers.

  • It does not access document.cookie or send headers automatically.
  • You must manually apply the generated strings to HTTP responses.
// cookie: Server-side string generation
const cookie = require('cookie');
const serialized = cookie.serialize('session', 'abc123', {
  httpOnly: true,
  maxAge: 60 * 60 * 24 * 7
});
res.setHeader('Set-Cookie', serialized);

js-cookie is designed for browsers only.

  • It directly interacts with document.cookie.
  • It will not work in Node.js environments without a DOM shim.
// js-cookie: Browser-side direct access
import Cookies from 'js-cookie';

Cookies.set('session', 'abc123', {
  expires: 7,
  secure: true
});

universal-cookie works in both environments.

  • It detects the environment and uses headers on the server or document.cookie in the browser.
  • Often used with React to share state during hydration.
// universal-cookie: Isomorphic access
import Cookies from 'universal-cookie';

const cookies = new Cookies();
cookies.set('session', 'abc123', {
  maxAge: 60 * 60 * 24 * 7,
  path: '/'
});

πŸ› οΈ API Interaction: Strings vs Direct Access

The level of abstraction determines how much boilerplate code you write.

cookie returns raw strings.

  • You get a string back from serialize that you must assign yourself.
  • You get an object from parse but must pass the header string manually.
// cookie: Manual parsing
const parsed = cookie.parse(req.headers.cookie || '');
const session = parsed.session;

js-cookie handles access internally.

  • You call get and it reads from the browser automatically.
  • No need to pass header strings or response objects.
// js-cookie: Automatic access
const session = Cookies.get('session');

universal-cookie abstracts the source.

  • You call get and it checks server cookies or browser cookies based on context.
  • Requires initialization to ensure server-side data is passed correctly.
// universal-cookie: Context-aware access
const cookies = new Cookies(req, res); // Pass req/res on server
const session = cookies.get('session');

⏱️ Configuration: Expiration and Attributes

Handling time and security attributes differs slightly between packages.

cookie uses standard HTTP attributes.

  • Uses maxAge in seconds.
  • Supports all standard flags like httpOnly, secure, sameSite.
// cookie: Standard HTTP options
const str = cookie.serialize('id', '1', {
  maxAge: 3600,
  httpOnly: true,
  sameSite: 'strict'
});

js-cookie simplifies time handling.

  • Uses expires which accepts a number (days) or a Date object.
  • Defaults to session cookie if no expiration is set.
// js-cookie: Human-friendly expiration
Cookies.set('id', '1', {
  expires: 7, // 7 days
  secure: true
});

universal-cookie mirrors server standards.

  • Uses maxAge in seconds like the cookie package.
  • Ensures consistency between server and client logic.
// universal-cookie: Server-consistent options
cookies.set('id', '1', {
  maxAge: 3600,
  path: '/'
});

βš›οΈ Framework Integration: React and SSR

Integration complexity grows when adding server-side rendering.

cookie has no framework bindings.

  • You must write your own hooks or context providers for React.
  • Best for Express or raw Node.js backends.
// cookie: Custom React hook required
// Developer must create context to pass parsed cookies to components

js-cookie is client-only.

  • Cannot read cookies during server rendering.
  • May cause hydration mismatches if used during initial render.
// js-cookie: Client-side only
// Will return undefined during server-side rendering
const value = Cookies.get('theme'); 

universal-cookie includes React bindings.

  • Provides CookiesProvider to share cookies across components.
  • Includes hooks like useCookies for functional components.
// universal-cookie: React integration
import { useCookies } from 'universal-cookie';

function Component() {
  const [cookies] = useCookies(['theme']);
  return <div>{cookies.theme}</div>;
}

🌐 Real-World Scenarios

Scenario 1: Custom Node.js API Server

You are building a raw HTTP server without a framework like Express.

  • βœ… Best choice: cookie
  • Why? You need to manually construct Set-Cookie headers without extra overhead.
// Using cookie package
const header = cookie.serialize('token', 'xyz', { httpOnly: true });
res.writeHead(200, { 'Set-Cookie': header });

Scenario 2: Standard Client-Side Dashboard

You are building a React app hosted on static storage (e.g., S3) with no SSR.

  • βœ… Best choice: js-cookie
  • Why? It is lightweight, handles encoding safely, and works immediately in the browser.
// Using js-cookie
Cookies.set('preferences', { darkMode: true }, { expires: 365 });

Scenario 3: Next.js or React SSR App

You need to read authentication cookies during server rendering to fetch user data.

  • βœ… Best choice: universal-cookie
  • Why? It allows reading cookies on the server before hydration to prevent mismatches.
// Using universal-cookie
const cookies = new Cookies(req.headers.cookie);
const user = await fetchUser(cookies.get('auth_token'));

πŸ“Œ Summary Table

Featurecookiejs-cookieuniversal-cookie
EnvironmentπŸ–₯️ Node.js Server🌐 Browser OnlyπŸ”„ Isomorphic (Both)
Access Method🧡 String Parse/SerializeπŸ“– Direct document.cookie🎭 Abstracted Context
Expiration⏱️ maxAge (seconds)πŸ“… expires (days/Date)⏱️ maxAge (seconds)
React Support❌ None❌ Noneβœ… Hooks & Provider
Auto Encoding❌ Manualβœ… Built-inβœ… Built-in

πŸ’‘ Final Recommendation

cookie is the foundation tool 🧱 β€” best for backend engineers building custom servers who need precise control over header strings without hidden magic.

js-cookie is the frontend staple πŸͺ β€” ideal for standard web applications where simplicity and reliability in the browser are the top priorities.

universal-cookie is the SSR bridge πŸŒ‰ β€” useful for React teams needing shared state between server and client, though teams should monitor its maintenance status for long-term projects.

Final Thought: All three packages solve the same problem but at different layers of the stack. Match the tool to your environment β€” server, client, or both β€” to avoid unnecessary complexity.

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

  • cookie:

    Choose cookie when building low-level Node.js servers or middleware where you need full control over HTTP header strings. It is ideal for custom server implementations where you manually handle Set-Cookie headers and request parsing without extra abstractions.

  • js-cookie:

    Choose js-cookie for client-side only applications that need a simple, reliable API for managing browser cookies. It handles encoding and expiration dates automatically, making it perfect for standard web apps that do not require server-side rendering integration.

  • universal-cookie:

    Choose universal-cookie for React projects requiring isomorphic cookie access across server and client. It is suitable for SSR setups, but teams should verify current maintenance status before committing to it for long-term enterprise projects.

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

const cookie = require("cookie");
// 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.stringify({ 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 is the global encodeURIComponent.

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.

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