cookie vs js-cookie vs cookie-parser vs cookies vs universal-cookie vs react-cookie
Cookie Management in Web Development
cookiejs-cookiecookie-parsercookiesuniversal-cookiereact-cookieSimilar Packages:
Cookie Management in Web Development

Cookie management libraries in JavaScript provide developers with tools to create, read, and delete cookies in a web browser. Cookies are small pieces of data stored on the client side, often used for session management, user tracking, and storing preferences. These libraries simplify cookie handling by providing easy-to-use APIs, ensuring proper encoding and decoding of cookie values, and handling issues like cookie expiration and path scoping. They are essential for building web applications that require persistent data storage on the client side.

Npm Package Weekly Downloads Trend
3 Years
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
cookie91,965,8671,44346.5 kB16a year agoMIT
js-cookie15,684,68622,75826.2 kB33 years agoMIT
cookie-parser5,455,6962,01713 kB28a year agoMIT
cookies5,080,2781,29922.4 kB352 years agoMIT
universal-cookie1,870,85320354.4 kB198 months agoMIT
react-cookie831,28120371.3 kB198 months agoMIT
Feature Comparison: cookie vs js-cookie vs cookie-parser vs cookies vs universal-cookie vs react-cookie

Cookie Parsing and Serialization

  • cookie:

    cookie provides simple functions for parsing and serializing cookie strings. It does not handle cookies directly but offers utilities for working with cookie data.

  • js-cookie:

    js-cookie provides a simple and intuitive API for creating, reading, and deleting cookies. It handles encoding and decoding of cookie values, making it easy to work with special characters.

  • cookie-parser:

    cookie-parser automatically parses the Cookie header from incoming requests and populates a cookies object on the request. It is designed for use with Express.js and simplifies access to cookie values.

  • cookies:

    cookies offers a straightforward API for setting, getting, and deleting cookies. It handles parsing and serialization, making it easy to work with cookie data.

  • universal-cookie:

    universal-cookie automatically parses cookies from the document or request (for server-side). It provides a simple API for accessing and manipulating cookies, making it versatile for both client and server environments.

  • react-cookie:

    react-cookie leverages js-cookie for cookie management but adds a React-friendly interface. It provides hooks and components for accessing and manipulating cookies within a React application.

Server-Side vs Client-Side Support

  • cookie:

    cookie is primarily a server-side library, but its parsing and serialization functions can be used in any JavaScript environment.

  • js-cookie:

    js-cookie is a client-side library focused on managing cookies in the browser. It does not provide server-side functionality.

  • cookie-parser:

    cookie-parser is designed for server-side use with Express.js. It parses cookies from incoming requests and is not intended for client-side use.

  • cookies:

    cookies supports both server-side and client-side cookie management, making it a versatile choice for full-stack applications.

  • universal-cookie:

    universal-cookie supports both client-side and server-side cookie management, making it suitable for universal (isomorphic) applications.

  • react-cookie:

    react-cookie is designed for client-side use in React applications. It does not provide server-side cookie management.

Integration with Frameworks

  • cookie:

    cookie is a standalone library with no dependencies, making it easy to integrate into any project.

  • js-cookie:

    js-cookie is a lightweight library that can be easily integrated into any web application or framework.

  • cookie-parser:

    cookie-parser is middleware for Express.js, making it easy to integrate into Express applications for automatic cookie parsing.

  • cookies:

    cookies can be used in any JavaScript environment and integrates well with both server-side and client-side frameworks.

  • universal-cookie:

    universal-cookie is designed to work well with React and other frameworks, providing a simple API that can be easily integrated into any application.

  • react-cookie:

    react-cookie is specifically designed for React applications, providing hooks and components for seamless integration with React's component model.

Ease of Use: Code Examples

  • cookie:

    Parsing and Serializing Cookies with cookie

    const cookie = require('cookie');
    
    // Parsing a cookie string
    const cookieString = 'name=John; age=30';
    const parsedCookies = cookie.parse(cookieString);
    console.log(parsedCookies); // { name: 'John', age: '30' }
    
    // Serializing a cookie
    const serializedCookie = cookie.serialize('name', 'Jane', { maxAge: 3600 });
    console.log(serializedCookie); // name=Jane; Max-Age=3600
    
  • js-cookie:

    Managing Cookies with js-cookie

    // Import the js-cookie library
    import Cookies from 'js-cookie';
    
    // Set a cookie
    Cookies.set('name', 'John', { expires: 7 }); // Expires in 7 days
    
    // Get a cookie
    const name = Cookies.get('name');
    console.log('Cookie:', name);
    
    // Delete a cookie
    Cookies.remove('name');
    
  • cookie-parser:

    Using cookie-parser Middleware in Express

    const express = require('express');
    const cookieParser = require('cookie-parser');
    
    const app = express();
    app.use(cookieParser()); // Use cookie-parser middleware
    
    app.get('/', (req, res) => {
      // Access parsed cookies from req.cookies
      console.log(req.cookies); // { name: 'John', age: '30' }
      res.send('Cookies parsed!');
    });
    
    app.listen(3000, () => {
      console.log('Server running on http://localhost:3000');
    });
    
  • cookies:

    Cookie Management with cookies Library

    const Cookies = require('cookies');
    const http = require('http');
    
    const server = http.createServer((req, res) => {
      const cookies = new Cookies(req, res);
    
      // Set a cookie
      cookies.set('name', 'John', { httpOnly: true });
    
      // Get a cookie
      const name = cookies.get('name');
      console.log('Cookie:', name);
    
      // Delete a cookie
      cookies.set('name');
    
      res.end('Cookie operations done!');
    });
    
    server.listen(3000, () => {
      console.log('Server running on http://localhost:3000');
    });
    
  • universal-cookie:

    Using universal-cookie for Cookie Management

    import React from 'react';
    import Cookies from 'universal-cookie';
    
    const cookies = new Cookies();
    
    // Set a cookie
    cookies.set('name', 'John', { path: '/' });
    
    // Get a cookie
    const name = cookies.get('name');
    console.log('Cookie:', name);
    
    // Delete a cookie
    cookies.remove('name');
    
  • react-cookie:

    Using react-cookie in a React Component

    import React from 'react';
    import { useCookies } from 'react-cookie';
    
    const MyComponent = () => {
      const [cookies, setCookie, removeCookie] = useCookies(['name']);
    
      // Set a cookie
      setCookie('name', 'John', { path: '/' });
    
      // Get a cookie
      const name = cookies.name;
      console.log('Cookie:', name);
    
      // Delete a cookie
      removeCookie('name');
    
      return <div>Check the console for cookie operations!</div>;
    };
    
    export default MyComponent;
    
How to Choose: cookie vs js-cookie vs cookie-parser vs cookies vs universal-cookie vs react-cookie
  • cookie:

    Choose cookie if you need a simple, lightweight library for parsing and serializing cookies. It is ideal for server-side applications or middleware where you want to handle cookies without any dependencies.

  • js-cookie:

    Choose js-cookie if you need a lightweight and user-friendly library for managing cookies in the browser. It has a simple API for creating, reading, and deleting cookies, with support for expiration, path, domain, and secure attributes.

  • cookie-parser:

    Choose cookie-parser if you are working with Express.js and need middleware to automatically parse cookies from incoming requests. It adds a cookies object to the request, making it easy to access cookie values.

  • cookies:

    Choose cookies if you want a comprehensive solution for both server-side and client-side cookie management. It provides a simple API for setting, getting, and deleting cookies, along with support for secure and HTTP-only flags.

  • universal-cookie:

    Choose universal-cookie if you need a versatile cookie management solution that works in both client and server environments. It supports React, provides a simple API for cookie manipulation, and handles cookie parsing and serialization automatically.

  • react-cookie:

    Choose react-cookie if you are building a React application and need a library that integrates seamlessly with React. It provides hooks and components for managing cookies, making it easy to work with cookies in a declarative way.

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.parse(str, options)

Parse a HTTP Cookie header string and returning 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 cookies = cookie.parse("foo=bar; equation=E%3Dmc%5E2");
// { foo: 'bar', equation: 'E=mc^2' }

Options

cookie.parse accepts these properties in the options object.

decode

Specifies a function that will be used to decode a cookie-value. Since the value of a cookie has a limited character set (and must be a simple string), this function can be used to decode a previously-encoded cookie value into a JavaScript string.

The default 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.

cookie.serialize(name, value, options)

Serialize a cookie name-value pair into a Set-Cookie header string. The name argument is the name for the cookie, the value argument is the value to set the cookie to, and the options argument is an optional object containing additional serialization options.

const setCookie = cookie.serialize("foo", "bar");
// foo=bar

Options

cookie.serialize accepts these properties in the options object.

encode

Specifies a function that will be used to encode a cookie-value. Since value of a cookie has a limited character set (and must be a simple string), this function can be used to encode a value into a string suited for a cookie's value, and should mirror decode when parsing.

The default function is the global encodeURIComponent.

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 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 a 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.

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.serialize("name", 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.parse(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