react-cookie vs js-cookie vs universal-cookie vs universal-cookie-express
フロントエンドおよびフルスタックアプリケーションにおけるクッキー操作ライブラリの選択
react-cookiejs-cookieuniversal-cookieuniversal-cookie-express類似パッケージ:

フロントエンドおよびフルスタックアプリケーションにおけるクッキー操作ライブラリの選択

js-cookiereact-cookieuniversal-cookie、およびuniversal-cookie-expressは、JavaScript環境でHTTPクッキーを扱うためのnpmパッケージです。これらのライブラリは、ブラウザやNode.jsサーバー上でクッキーの読み書き・削除を行う共通の目的を持ちながら、対応する実行環境や統合方法に違いがあります。js-cookieは純粋なクライアントサイド向け軽量ライブラリであり、react-cookieはReactコンポーネントとの統合に特化しています。一方、universal-cookieはブラウザとNode.jsの両方で動作するユニバーサルなAPIを提供し、universal-cookie-expressはそのExpress.js用ミドルウェア拡張として設計されています。

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

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
react-cookie1,116,68821571.7 kB42ヶ月前MIT
js-cookie022,60025.9 kB417日前MIT
universal-cookie021563.7 kB42ヶ月前MIT
universal-cookie-express02155.51 kB42ヶ月前MIT

クッキー操作ライブラリ徹底比較:js-cookie、react-cookie、universal-cookie、universal-cookie-express

Webアプリケーションで認証トークンやユーザー設定などを保存する際、HTTPクッキーは依然として重要なストレージ手段です。しかし、ブラウザとサーバーでクッキーを一貫して扱うのは意外と難しいものです。ここでは、代表的な4つのnpmパッケージ — js-cookiereact-cookieuniversal-cookieuniversal-cookie-express — の技術的違いを、実際のコードを交えながら詳しく解説します。

🍪 基本的なクッキー操作:書き込み・読み取り・削除

まず、各ライブラリで基本的なクッキー操作がどのように行われるかを見てみましょう。

js-cookie(クライアントサイド専用)

import Cookies from 'js-cookie';

// 書き込み
Cookies.set('user', 'john', { expires: 7 });

// 読み取り
const user = Cookies.get('user');

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

js-cookieはシンプルで直感的です。すべての操作が静的メソッド経由で行われ、追加のセットアップは不要です。

react-cookie(React統合)

import { useCookies } from 'react-cookie';

function MyComponent() {
  const [cookies, setCookie, removeCookie] = useCookies(['user']);

  // 書き込み
  setCookie('user', 'john', { path: '/' });

  // 読み取り(現在の値はcookies.user)
  console.log(cookies.user);

  // 削除
  removeCookie('user');

  return <div>{cookies.user}</div>;
}

react-cookieはReactの状態管理と連動しており、クッキーが変更されると自動的に再レンダリングされます。

universal-cookie(ユニバーサル対応)

// クライアントサイドまたはNode.jsで同じコードが動作
import Cookies from 'universal-cookie';

const cookies = new Cookies();

// 書き込み
cookies.set('user', 'john', { path: '/' });

// 読み取り
const user = cookies.get('user');

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

universal-cookieはインスタンスベースで、環境に応じて内部でdocument.cookieまたはreq.headers.cookie/res.setHeaderを使い分けます。

universal-cookie-express(Express用ミドルウェア)

// Expressサーバー側での使用例
import { Cookies } from 'universal-cookie';
import cookieMiddleware from 'universal-cookie-express';

app.use(cookieMiddleware());

app.get('/login', (req, res) => {
  const cookies = new Cookies(req.headers.cookie, res);
  cookies.set('auth-token', 'abc123', { httpOnly: true });
  // ミドルウェアにより、レスポンス時に自動的にSet-Cookieヘッダーが設定される
  res.send('Logged in');
});

このパッケージ自体は操作メソッドを提供せず、universal-cookieインスタンスが持つクッキーをExpressのレスポンスに適用する役割を果たします。

🌐 環境対応:ブラウザ vs サーバー

クライアントサイド専用 vs ユニバーサル

  • js-cookie:ブラウザのdocument.cookieに直接アクセスするため、Node.js環境では動作しません。Next.jsなどのSSRフレームワークで使うと、サーバーサイドレンダリング中にエラーが発生します。

  • react-cookie:内部でuniversal-cookieを使用しているため、理論上はサーバーでも動作可能ですが、主にReactコンポーネント内での使用を想定しています。SSR時の初期化には特別な処理が必要です。

  • universal-cookie:コンストラクタにreqresを渡すことでNode.js環境でも動作します。例えばNext.jsのAPIルートでは以下のように使用できます。

// Next.js APIルート (/pages/api/login.js)
import { Cookies } from 'universal-cookie';

export default function handler(req, res) {
  const cookies = new Cookies(req.headers.cookie, res);
  cookies.set('token', 'xyz', { httpOnly: true });
  res.status(200).json({ success: true });
}
  • universal-cookie-express:Express.js専用のミドルウェアであり、他の環境では使用できません。

⚙️ React統合の深さ

react-cookieはReactのライフサイクルと密接に連携します。

// クッキー変更時に自動再レンダリング
function UserProfile() {
  const [cookies] = useCookies(['theme']);

  // cookies.themeが変更されると、このコンポーネントは再レンダリングされる
  return (
    <div className={cookies.theme || 'light'}>
      ユーザープロフィール
    </div>
  );
}

一方、js-cookieuniversal-cookieをReactで使う場合、手動でuseStateuseEffectを使って状態を同期する必要があります。

// js-cookieをReactで使う場合(手動同期が必要)
import { useState, useEffect } from 'react';
import Cookies from 'js-cookie';

function UserProfile() {
  const [theme, setTheme] = useState(Cookies.get('theme') || 'light');

  useEffect(() => {
    // 外部からクッキーが変更された場合の監視は自前実装が必要
    const handleStorageChange = () => {
      setTheme(Cookies.get('theme') || 'light');
    };
    window.addEventListener('storage', handleStorageChange);
    return () => window.removeEventListener('storage', handleStorageChange);
  }, []);

  return <div className={theme}>ユーザープロフィール</div>;
}

このように、Reactアプリでクッキーを「リアクティブな状態」として扱いたいならreact-cookieが便利ですが、単発の読み書きだけならjs-cookieで十分です。

🔒 セキュリティオプションのサポート

すべてのライブラリが、httpOnlysecuresameSiteなどのセキュリティ属性をサポートしていますが、設定方法に若干の違いがあります。

// js-cookie
Cookies.set('token', 'abc', {
  httpOnly: false, // js-cookieではhttpOnlyをfalseに固定(ブラウザ制限のため)
  secure: true,
  sameSite: 'strict'
});

// universal-cookie(Node.js環境)
cookies.set('token', 'abc', {
  httpOnly: true, // サーバー側ではtrueにできる
  secure: true,
  sameSite: 'strict'
});

重要な点として、js-cookieはクライアントサイドライブラリのため、httpOnly: trueのクッキーを設定も読み取りもできません。これはブラウザの仕様による制限です。httpOnlyクッキーが必要な場合は、必ずサーバー側(universal-cookie + universal-cookie-expressなど)で設定する必要があります。

🧩 アーキテクチャ上のトレードオフ

軽量さ vs 汎用性

  • js-cookie:バンドルサイズが非常に小さい(約1KB)。シンプルなフロントエンドアプリに最適。
  • react-cookie:ReactのContextとHooksのオーバーヘッドがあるため、js-cookieより重い。React専用機能が必要なければ無駄になる可能性あり。
  • universal-cookie:環境判定のロジックがあるため、js-cookieより若干大きいが、SSRやフルスタック対応が必要なら必須。
  • universal-cookie-express:Expressサーバーとの連携に特化した補助パッケージ。単独では意味がない。

初期化と状態管理

  • js-cookieuniversal-cookie(静的使用時)はグローバル状態を持ちません。
  • react-cookieは内部でReact Contextを使用するため、アプリケーション全体で1つのクッキー状態を共有します。
  • universal-cookieのインスタンスは明示的に作成する必要があり、複数のインスタンスを独立して管理できます(例:異なるドメイン用のクッキー)。

🛑 非推奨・メンテナンス状況について

執筆時点(2024年)で、これら4つのパッケージはいずれも非推奨(deprecated)ではなく、積極的にメンテナンスされています。GitHubリポジトリやnpmページに非推奨の警告は存在しません。

📊 まとめ:どのライブラリを選ぶべきか?

ユースケース推奨パッケージ理由
純粋なフロントエンド(React以外)js-cookie軽量でシンプル、余計な機能なし
Reactアプリでクッキーを状態として扱いたいreact-cookie自動再レンダリング、React Hooksとの親和性
Next.js/Nuxt.jsなどSSR対応が必要universal-cookieブラウザ/サーバー両対応、一貫したAPI
Expressサーバーと連携したフルスタックアプリuniversal-cookie + universal-cookie-expressサーバー側でのhttpOnlyクッキー設定が可能

💡 最終的なアドバイス

  • シンプルなフロントエンドだけjs-cookie
  • Reactでクッキーをリアクティブに使いたいreact-cookie
  • SSRやサーバー連携が必要universal-cookie(Expressなら追加でuniversal-cookie-express

クッキーはセキュリティに直結する要素です。特に認証トークンを保存する場合は、httpOnlysecure属性を忘れずに設定し、可能な限りサーバー側でクッキーを管理することを強く推奨します。その観点から、現代のフルスタックアプリケーションではuniversal-cookieが最もバランスの取れた選択肢と言えるでしょう。

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

  • react-cookie:

    react-cookieは、Reactアプリケーション内でクッキーを状態として扱いたい場合に適しています。React Contextとカスタムフック(useCookies)を活用して、コンポーネントツリー全体でクッキーの変更を自動的に反映できます。ただし、このライブラリは内部でuniversal-cookieに依存しており、純粋なクライアントサイド用途であればjs-cookieの方が軽量です。React専用の統合機能が必要ない場合は過剰な選択となる可能性があります。

  • js-cookie:

    js-cookieは、シンプルで軽量なクライアントサイド専用のクッキーライブラリが必要な場合に最適です。React以外のフレームワーク(Vue、Svelte、Vanilla JSなど)や、最小限の依存関係でクッキー操作を行いたいプロジェクトに向いています。ただし、サーバーサイドレンダリング(SSR)やNode.js環境での使用はサポートされていないため、Next.jsやNuxt.jsなどのハイブリッドフレームワークでは注意が必要です。

  • universal-cookie:

    universal-cookieは、同じコードベースでブラウザとNode.js(例:Next.js APIルートやExpressサーバー)の両方でクッキーを操作したい場合に最適です。環境に応じて自動的に動作を切り替えるユニバーサルAPIを提供するため、SSRやフルスタックアプリケーションでの一貫性のあるクッキー管理が可能です。ただし、クライアントサイドのみで使う場合はjs-cookieより若干オーバーヘッドがあります。

  • universal-cookie-express:

    universal-cookie-expressは、universal-cookieで生成されたクッキーをExpress.jsサーバーで処理するためのミドルウェアです。具体的には、レスポンス時にクッキーを自動的に設定する機能を提供します。このパッケージ単体では使用できず、必ずuniversal-cookieと併用する必要があります。Expressベースのバックエンドとフロントエンドでクッキーを共有するアーキテクチャを採用している場合にのみ検討してください。

react-cookie のREADME

react-cookie

Universal cookies for React
Test Status

Integrations

Minimum requirement

react-cookie @ v3.0+

  • React.js >= 16.3.0 (new context API + forward ref)

react-cookie @ v0.0-v2.2

  • React.js >= 15

Getting started

npm install react-cookie

or in the browser (global variable ReactCookie):

<script
  crossorigin
  src="https://unpkg.com/react@16/umd/react.production.js"
></script>
<script
  crossorigin
  src="https://unpkg.com/universal-cookie@7/umd/universalCookie.min.js"
></script>
<script
  crossorigin
  src="https://unpkg.com/react-cookie@7/umd/reactCookie.min.js"
></script>

<CookiesProvider defaultSetOptions />

Set the user cookies

On the server, the cookies props must be set using req.universalCookies or new Cookie(cookieHeader)

  • defaultSetOptions: You can set default values for when setting cookies.

useCookies([dependencies], [options])

Access and modify cookies using React hooks.

const [cookies, setCookie, removeCookie] = useCookies(['cookie-name']);

React hooks are available starting from React 16.8

dependencies (optional)

Let you optionally specify a list of cookie names your component depend on or that should trigger a re-render. If unspecified, it will render on every cookie change.

options (optional)

  • options (object):
    • doNotParse (boolean): do not convert the cookie into an object no matter what
    • doNotUpdate (boolean): do not update the cookies when the component mounts
const [cookies, setCookie, removeCookie] = useCookies(['cookie-name'], {
  doNotParse: true,
});

cookies

Javascript object with all your cookies. The key is the cookie name.

setCookie(name, value, [options])

Set a cookie value

  • name (string): cookie name
  • value (string|object): save the value and stringify the object if needed
  • options (object): Support all the cookie options from RFC 6265
    • path (string): cookie path, use / as the path if you want your cookie to be accessible on all pages
    • expires (Date): absolute expiration date for the cookie
    • maxAge (number): relative max age of the cookie from when the client receives it in seconds
    • domain (string): domain for the cookie (sub.domain.com or .allsubdomains.com)
    • secure (boolean): Is only accessible through HTTPS?
    • httpOnly (boolean): Can only the server access the cookie? Note: You cannot get or set httpOnly cookies from the browser, only the server.
    • sameSite (boolean|none|lax|strict): Strict or Lax enforcement
    • partitioned (boolean): Indicates that the cookie should be stored using partitioned storage

removeCookie(name, [options])

Remove a cookie

  • name (string): cookie name
  • options (object): Support all the cookie options from RFC 6265
    • path (string): cookie path, use / as the path if you want your cookie to be accessible on all pages
    • expires (Date): absolute expiration date for the cookie
    • maxAge (number): relative max age of the cookie from when the client receives it in seconds
    • domain (string): domain for the cookie (sub.domain.com or .allsubdomains.com)
    • secure (boolean): Is only accessible through HTTPS?
    • httpOnly (boolean): Can only the server access the cookie? Note: You cannot get or set httpOnly cookies from the browser, only the server.
    • sameSite (boolean|none|lax|strict): Strict or Lax enforcement
    • partitioned (boolean): Indicates that the cookie should be stored using partitioned storage

updateCookies()

Read back the cookies from the browser and triggers the change listeners. This should normally not be necessary because this library detects cookie changes automatically.

withCookies(Component)

Give access to your cookies anywhere. Add the following props to your component:

  • cookies: Cookies instance allowing you to get, set and remove cookies.
  • allCookies: All your current cookies in an object.

Your original static properties will be hoisted on the returned component. You can also access the original component by using the WrappedComponent static property. Example:

function MyComponent() {
  return null;
}
const NewComponent = withCookies(MyComponent);
NewComponent.WrappedComponent === MyComponent;

Cookies

get(name, [options])

Get a cookie value

  • name (string): cookie name
  • options (object):
    • doNotParse (boolean): do not convert the cookie into an object no matter what

getAll([options])

Get all cookies

  • options (object):
    • doNotParse (boolean): do not convert the cookie into an object no matter what

set(name, value, [options])

Set a cookie value

  • name (string): cookie name
  • value (string|object): save the value and stringify the object if needed
  • options (object): Support all the cookie options from RFC 6265
    • path (string): cookie path, use / as the path if you want your cookie to be accessible on all pages
    • expires (Date): absolute expiration date for the cookie
    • maxAge (number): relative max age of the cookie from when the client receives it in seconds
    • domain (string): domain for the cookie (sub.domain.com or .allsubdomains.com)
    • secure (boolean): Is only accessible through HTTPS?
    • httpOnly (boolean): Can only the server access the cookie? Note: You cannot get or set httpOnly cookies from the browser, only the server.
    • sameSite (boolean|none|lax|strict): Strict or Lax enforcement
    • partitioned (boolean): Indicates that the cookie should be stored using partitioned storage

remove(name, [options])

Remove a cookie

  • name (string): cookie name
  • options (object): Support all the cookie options from RFC 6265
    • path (string): cookie path, use / as the path if you want your cookie to be accessible on all pages
    • expires (Date): absolute expiration date for the cookie
    • maxAge (number): relative max age of the cookie from when the client receives it in seconds
    • domain (string): domain for the cookie (sub.domain.com or .allsubdomains.com)
    • secure (boolean): Is only accessible through HTTPS?
    • httpOnly (boolean): Can only the server access the cookie? Note: You cannot get or set httpOnly cookies from the browser, only the server.
    • sameSite (boolean|none|lax|strict): Strict or Lax enforcement
    • partitioned (boolean): Indicates that the cookie should be stored using partitioned storage

Simple Example with React hooks

// Root.tsx
import React from 'react';
import App from './App';
import { CookiesProvider } from 'react-cookie';

export default function Root(): React.ReactElement {
  return (
    <CookiesProvider defaultSetOptions={{ path: '/' }}>
      <App />
    </CookiesProvider>
  );
}
// App.tsx
import React from 'react';
import { useCookies } from 'react-cookie';

import NameForm from './NameForm';

interface CookieValues {
  name?: string;
}

function App(): React.ReactElement {
  const [cookies, setCookie] = useCookies<'name', CookieValues>(['name']);

  function onChange(newName: string): void {
    setCookie('name', newName);
  }

  return (
    <div>
      <NameForm name={cookies.name || ''} onChange={onChange} />
      {cookies.name && <h1>Hello {cookies.name}!</h1>}
    </div>
  );
}

export default App;

Simple Example with Higher-Order Component

// Root.tsx
import React from 'react';
import App from './App';
import { CookiesProvider } from 'react-cookie';

export default function Root(): React.ReactElement {
  return (
    <CookiesProvider>
      <App />
    </CookiesProvider>
  );
}
// App.tsx
import React, { Component } from 'react';
import { withCookies, Cookies, ReactCookieProps } from 'react-cookie';

import NameForm from './NameForm';

interface State {
  name: string;
}

interface Props extends ReactCookieProps {
  cookies: Cookies;
}

class App extends Component<Props, State> {
  constructor(props: Props) {
    super(props);

    const { cookies } = props;
    this.state = {
      name: cookies.get('name') || 'Ben',
    };
  }

  handleNameChange(name: string): void {
    const { cookies } = this.props;

    cookies.set('name', name, { path: '/' });
    this.setState({ name });
  }

  render(): React.ReactNode {
    const { name } = this.state;

    return (
      <div>
        <NameForm name={name} onChange={this.handleNameChange.bind(this)} />
        {this.state.name && <h1>Hello {this.state.name}!</h1>}
      </div>
    );
  }
}

export default withCookies(App);

Server-Rendering Example

// src/components/App.ts
import React from 'react';
import { useCookies } from 'react-cookie';

import NameForm from './NameForm';

function App() {
  const [cookies, setCookie] = useCookies(['name']);

  function onChange(newName: string) {
    setCookie('name', newName, { path: '/' });
  }

  return (
    <div>
      <NameForm name={cookies.name} onChange={onChange} />
      {cookies.name && <h1>Hello {cookies.name}!</h1>}
    </div>
  );
}

export default App;
// src/server.ts
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { CookiesProvider } from 'react-cookie';
import { Request, Response } from 'express';

import Html from './components/Html';
import App from './components/App';

export default function middleware(req: Request, res: Response) {
  const markup = ReactDOMServer.renderToString(
    <CookiesProvider cookies={req.universalCookies}>
      <App />
    </CookiesProvider>,
  );

  const html = ReactDOMServer.renderToStaticMarkup(<Html markup={markup} />);

  res.send('<!DOCTYPE html>' + html);
}
// src/client.ts
import React from 'react';
import { createRoot } from 'react-dom/client';
import { CookiesProvider } from 'react-cookie';

import App from './components/App';

const root = createRoot(document.getElementById('main-app'));

root.render(
  <CookiesProvider>
    <App />
  </CookiesProvider>,
);
// server.ts
import express from 'express';
import serverMiddleware from './src/server';
import cookiesMiddleware from 'universal-cookie-express';

const app = express();

app.use(cookiesMiddleware()).use(serverMiddleware);

app.listen(8080, function () {
  console.log('Listening on 8080...');
});