react-cookie vs cookie vs js-cookie vs universal-cookie
クッキー管理ライブラリ
react-cookiecookiejs-cookieuniversal-cookie

クッキー管理ライブラリ

クッキー管理ライブラリは、ウェブアプリケーションにおいてクッキーを簡単に操作するためのツールです。これらのライブラリは、クッキーの設定、取得、削除を簡素化し、ブラウザのクッキー機能を利用する際の複雑さを軽減します。特に、クッキーはユーザーのセッション管理や状態保持に重要な役割を果たします。

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

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
react-cookie893,51021378.6 kB34日前MIT
cookie01,47860.5 kB134ヶ月前MIT
js-cookie022,77826.2 kB33年前MIT
universal-cookie021365.6 kB34日前MIT

機能比較: react-cookie vs cookie vs js-cookie vs universal-cookie

APIのシンプルさ

  • react-cookie:

    Reactのコンポーネントとしてクッキーを管理できるため、状態管理と統合されており、Reactのライフサイクルに沿った使い方ができます。

  • cookie:

    非常にシンプルなAPIを提供しており、クッキーの設定や取得が直感的に行えます。

  • js-cookie:

    簡潔で使いやすいAPIを持ち、クッキーの操作が容易です。オプションを指定することで、さまざまな設定が可能です。

  • universal-cookie:

    サーバーサイドとクライアントサイドの両方で一貫したAPIを提供しており、両方の環境で同じ方法でクッキーを扱えます。

ブラウザ互換性

  • react-cookie:

    Reactアプリケーションに特化しているため、ブラウザ互換性はjs-cookieに依存しています。

  • cookie:

    Node.js環境での使用を前提としているため、ブラウザ互換性は考慮されていません。

  • js-cookie:

    主要なブラウザに幅広く対応しており、古いブラウザでも動作します。

  • universal-cookie:

    サーバーサイドとクライアントサイドの両方で動作するため、ブラウザ互換性に優れています。

セッション管理

  • react-cookie:

    Reactの状態管理と組み合わせることで、セッションの状態を簡単に管理できます。

  • cookie:

    セッション管理のための基本的な機能を提供しますが、追加の機能はありません。

  • js-cookie:

    クッキーの有効期限を設定することで、セッション管理が容易になります。

  • universal-cookie:

    サーバーサイドでのセッション管理が可能で、クライアントサイドと連携して効果的なセッション管理を実現します。

ユースケース

  • react-cookie:

    Reactアプリケーション内でのクッキー管理に特化しており、状態を保持するために使用されます。

  • cookie:

    Node.jsバックエンドでのクッキー操作に最適です。

  • js-cookie:

    フロントエンドでのクッキー操作に適しており、特にシンプルなウェブアプリケーションに向いています。

  • universal-cookie:

    ユニバーサルアプリケーションにおいて、サーバーサイドとクライアントサイドでのクッキー管理を必要とする場合に最適です。

拡張性

  • react-cookie:

    Reactのエコシステムに統合されており、他のReactライブラリと組み合わせて拡張可能です。

  • cookie:

    基本的な機能のみを提供しており、拡張性は限られています。

  • js-cookie:

    シンプルなAPIにより、他のライブラリと組み合わせて使用することが容易です。

  • universal-cookie:

    サーバーサイドとクライアントサイドの両方で使用できるため、拡張性が高く、複雑なユースケースにも対応できます。

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

  • react-cookie:

    Reactアプリケーション内でクッキーを管理したい場合に適しています。Reactのライフサイクルに統合されており、コンポーネントベースの設計にマッチします。

  • cookie:

    シンプルなクッキー操作が必要な場合や、軽量なライブラリを求めている場合に適しています。特に、Node.js環境での使用に向いています。

  • js-cookie:

    クライアントサイドでのクッキー操作を簡単に行いたい場合に最適です。シンプルなAPIを提供し、ブラウザの互換性も高いです。

  • universal-cookie:

    サーバーサイドとクライアントサイドの両方でクッキーを管理する必要がある場合に最適です。ユニバーサルアプリケーションに対応しており、SSR(サーバーサイドレンダリング)を考慮した設計です。

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...');
});