cookie vs js-cookie vs universal-cookie
JavaScript 環境における Cookie 管理戦略
cookiejs-cookieuniversal-cookie類似パッケージ:

JavaScript 環境における Cookie 管理戦略

cookiejs-cookieuniversal-cookie は、HTTP Cookie の処理を簡素化するライブラリですが、それぞれ想定される実行環境と役割が異なります。cookie は Node.js 向けの低レベルなパーサーであり、js-cookie はブラウザ専用のシンプル API を提供します。一方、universal-cookie はサーバーサイドレンダリング(SSR)に対応し、クライアントとサーバーで共通のインターフェースを提供します。

npmのダウンロードトレンド

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
cookie01,47660.5 kB135ヶ月前MIT
js-cookie022,62226.2 kB43年前MIT
universal-cookie021365.6 kB41ヶ月前MIT

JavaScript における Cookie 管理ライブラリの比較:cookie vs js-cookie vs universal-cookie

Web 開発において Cookie の扱いは、認証状態の保持やユーザー設定の保存など、重要な役割を果たします。しかし、実行環境がブラウザかサーバーかによって、適切なアプローチは大きく異なります。cookiejs-cookieuniversal-cookie の 3 つは、この問題を解決するための代表的なライブラリですが、それぞれ設計思想と適用範囲が明確に違います。

🌍 実行環境のサポート範囲

どの環境で動かすかは、ライブラリ選定の最初の基準になります。

cookie は Node.js 環境を主軸に設計されています。

  • 浏览器の document.cookie には直接アクセスしません。
  • 文字列のパーサーとシリアライザーとして機能します。
  • Express などのミドルウェア内部でよく使われます。
// cookie: 文字列の生成と解析のみ
import cookie from 'cookie';

// 生成(Set-Cookie ヘッダー値)
const serialized = cookie.serialize('user', 'alice', {
  httpOnly: true,
  maxAge: 60 * 60 * 24 * 7
});
// 手动でレスポンスヘッダーに設定する必要があります
res.setHeader('Set-Cookie', serialized);

// 解析(Cookie ヘッダー値)
const parsed = cookie.parse(req.headers.cookie || '');
console.log(parsed.user); // 'alice'

js-cookie はブラウザ環境に特化しています。

  • document.cookie を直接操作します。
  • Node.js 環境では document がないためエラーになります。
  • SSR 構成では使用できません。
// js-cookie: ブラウザ専用
import Cookies from 'js-cookie';

// 設定(自动で document.cookie に書き込み)
Cookies.set('user', 'alice', { expires: 7 });

// 取得
const user = Cookies.get('user');
console.log(user); // 'alice'

// 削除
Cookies.remove('user');

universal-cookie はサーバーとクライアントの両方に対応しています。

  • 内部で cookie パッケージを利用しつつ、ブラウザでは document.cookie を操作します。
  • SSR 時にリクエストヘッダーから Cookie を読み取れます。
  • 環境を気にせず同じ API を使えます。
// universal-cookie: 両環境対応
import Cookies from 'universal-cookie';

// インスタンス化(サーバー側では Cookie 文字列を渡す)
const cookies = new Cookies(req?.headers?.cookie);

// 設定(環境に合わせて自动で切り替え)
cookies.set('user', 'alice', { path: '/', maxAge: 3600 });

// 取得
const user = cookies.get('user');
console.log(user); // 'alice'

// 削除
cookies.remove('user');

🛠️ API デザインと操作性

ライブラリごとの API の使い勝手も、開発体験に直結します。

cookie は関数ベースの低レベル API です。

  • 状態を持たず、純粋な文字列変換を行います。
  • 設定オプションはオブジェクトで渡します。
  • 細かい制御が可能ですが、手動処理が増えます。
// cookie: 関数呼び出し
import cookie from 'cookie';

const str = cookie.serialize('token', 'xyz', { secure: true });
const obj = cookie.parse('token=xyz');

js-cookie は静的メソッドベースのシンプル API です。

  • インスタンス化不要で、すぐに使えます。
  • 引数が少なく、直感的です。
  • 高度な設定よりも簡便さを優先しています。
// js-cookie: 静的メソッド
import Cookies from 'js-cookie';

Cookies.set('token', 'xyz', { secure: true });
const val = Cookies.get('token');

universal-cookie はクラスインスタンスベースの API です。

  • 最初にインスタンスを作成する必要があります。
  • 複数の Cookie コンテキストを管理しやすいです。
  • React のコンテキスト API と組み合わせやすい構造です。
// universal-cookie: インスタンスメソッド
import Cookies from 'universal-cookie';

const cookies = new Cookies();
cookies.set('token', 'xyz', { secure: true });
const val = cookies.get('token');

🔒 セキュリティと設定オプション

セキュリティ設定の扱い方も、重要な比較ポイントです。

cookie はすべてのフラグを手动で設定します。

  • httpOnlysecuresameSite などを明示します。
  • 設定漏れを防ぐためには、ラッパー関数を作るのが一般的です。
// cookie: 手动設定
const opts = {
  httpOnly: true,
  secure: process.env.NODE_ENV === 'production',
  sameSite: 'strict'
};
const header = cookie.serialize('session', id, opts);

js-cookie は主要なオプションをサポートします。

  • expires、path、domain、secure、sameSite などを設定可能。
  • 浏览器の制限に従って動作します。
// js-cookie: オプション指定
Cookies.set('session', id, {
  secure: true,
  sameSite: 'strict',
  expires: 1
});

universal-cookiejs-cookie と似たオプション体系です。

  • サーバー側でもクライアント側でも同じオプションが使えます。
  • 環境による挙動の違いを吸収します。
// universal-cookie: オプション指定
cookies.set('session', id, {
  secure: true,
  sameSite: 'strict',
  maxAge: 3600
});

📊 比較サマリー

特徴cookiejs-cookieuniversal-cookie
主な環境Node.js浏览器両方(ユニバーサル)
API 形式関数(parse/serialize)静的メソッドクラスインスタンス
document.cookie操作しない直接操作自动操作(客户端)
SSR 対応可能(手動作業)不可対応(自动)
依存関係なしなしcookie に依存
用途ミドルウェア開発クライアント専用アプリReact/SSR アプリ

💡 最終的な推奨事項

プロジェクトのアーキテクチャに応じて、以下の基準で選択してください。

cookie は、Express や Koa などのサーバー側ミドルウェアを開発する場合に最適です — 自分で HTTP ヘッダーの制御を完全に行いたい時に使います。ただし、ブラウザ側で使うには追加の実装が必要です。

js-cookie は、Create React App や Vite などで構築する、サーバーレンダリング不要のシングルページアプリケーションに最適です — 手軽に導入でき、学習コストが低いのが魅力です。

universal-cookie は、Next.js や Remix など、サーバーとクライアントでコードを共有する現代の Web アプリケーションに最適です — 環境の違いを吸収してくれるため、バグの発生リスクを減らせます。

どのライブラリも目的が明確です。自分のプロジェクトがどこで動き、どのような制御を必要としているかを整理してから選定しましょう。

選び方: cookie vs js-cookie vs universal-cookie

  • cookie:

    Node.js ミドルウェア開発や、Cookie 文字列の解析・生成のみが必要な場合に選択します。ブラウザの document.cookie を直接操作しないため、制御を完全に自分で行いたいアーキテクチャに適しています。HTTP ヘッダーの処理を手动で行う余裕があるチーム向けです。

  • js-cookie:

    SSR を使用しない純粋なクライアントサイドアプリケーションで選択します。API が非常にシンプルで軽量であり、ブラウザ環境での Cookie 操作を最小のコードで実現できます。サーバー側での処理が必要ない場合に最適です。

  • universal-cookie:

    Next.js などの SSR 環境や、ユニバーサルアプリケーションで選択します。サーバーとクライアントで同じコードを動かす必要がある場合、環境を気にせずに Cookie を扱えるため開発効率が向上します。React 生態系との親和性も高いです。

cookie のREADME

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