cookies vs cookie vs cookie-parser vs js-cookie vs react-cookie vs universal-cookie
Cookie Management in Web Development
cookiescookiecookie-parserjs-cookiereact-cookieuniversal-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
cookies7,930,2251,30122.4 kB342 years agoMIT
cookie01,47860.5 kB165 months agoMIT
cookie-parser02,02713 kB302 years agoMIT
js-cookie022,59726.2 kB33 years agoMIT
react-cookie021471.7 kB26 days agoMIT
universal-cookie021463.7 kB26 days agoMIT

Feature Comparison: cookies vs cookie vs cookie-parser vs js-cookie vs react-cookie vs universal-cookie

Cookie Parsing and Serialization

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

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

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

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

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

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

Server-Side vs Client-Side Support

  • cookies:

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

  • cookie:

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

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

  • js-cookie:

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

  • react-cookie:

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

  • universal-cookie:

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

Integration with Frameworks

  • cookies:

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

  • cookie:

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

  • cookie-parser:

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

  • js-cookie:

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

  • react-cookie:

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

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

Ease of Use: Code Examples

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

How to Choose: cookies vs cookie vs cookie-parser vs js-cookie vs react-cookie vs universal-cookie

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

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

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

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

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

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

README for cookies

Cookies

NPM Version NPM Downloads Node.js Version Build Status Test Coverage

Cookies is a node.js module for getting and setting HTTP(S) cookies. Cookies can be signed to prevent tampering, using Keygrip. It can be used with the built-in node.js HTTP library, or as Connect/Express middleware.

Install

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install cookies

Features

  • Lazy: Since cookie verification against multiple keys could be expensive, cookies are only verified lazily when accessed, not eagerly on each request.

  • Secure: All cookies are httponly by default, and cookies sent over SSL are secure by default. An error will be thrown if you try to send secure cookies over an insecure socket.

  • Unobtrusive: Signed cookies are stored the same way as unsigned cookies, instead of in an obfuscated signing format. An additional signature cookie is stored for each signed cookie, using a standard naming convention (cookie-name.sig). This allows other libraries to access the original cookies without having to know the signing mechanism.

  • Agnostic: This library is optimized for use with Keygrip, but does not require it; you can implement your own signing scheme instead if you like and use this library only to read/write cookies. Factoring the signing into a separate library encourages code reuse and allows you to use the same signing library for other areas where signing is needed, such as in URLs.

API

new Cookies(request, response [, options])

Create a new cookie jar for a given request and response pair. The request argument is a Node.js HTTP incoming request object and the response argument is a Node.js HTTP server response object.

A Keygrip object or an array of keys can optionally be passed as options.keys to enable cryptographic signing based on SHA1 HMAC, using rotated credentials.

A Boolean can optionally be passed as options.secure to explicitally specify if the connection is secure, rather than this module examining request.

Note that since this only saves parameters without any other processing, it is very lightweight. Cookies are only parsed on demand when they are accessed.

Cookies.express(keys)

This adds cookie support as a Connect middleware layer for use in Express apps, allowing inbound cookies to be read using req.cookies.get and outbound cookies to be set using res.cookies.set.

cookies.get(name [, options])

This extracts the cookie with the given name from the Cookie header in the request. If such a cookie exists, its value is returned. Otherwise, nothing is returned.

{ signed: true } can optionally be passed as the second parameter options. In this case, a signature cookie (a cookie of same name ending with the .sig suffix appended) is fetched. If no such cookie exists, nothing is returned.

If the signature cookie does exist, the provided Keygrip object is used to check whether the hash of cookie-name=cookie-value matches that of any registered key:

  • If the signature cookie hash matches the first key, the original cookie value is returned.
  • If the signature cookie hash matches any other key, the original cookie value is returned AND an outbound header is set to update the signature cookie's value to the hash of the first key. This enables automatic freshening of signature cookies that have become stale due to key rotation.
  • If the signature cookie hash does not match any key, nothing is returned, and an outbound header with an expired date is used to delete the cookie.

cookies.set(name [, values [, options]])

This sets the given cookie in the response and returns the current context to allow chaining.

If the value is omitted, an outbound header with an expired date is used to delete the cookie.

If the options object is provided, it will be used to generate the outbound cookie header as follows:

  • maxAge: a number representing the milliseconds from Date.now() for expiry
  • expires: a Date object indicating the cookie's expiration date (expires at the end of session by default).
  • path: a string indicating the path of the cookie (/ by default).
  • domain: a string indicating the domain of the cookie (no default).
  • secure: a boolean indicating whether the cookie is only to be sent over HTTPS (false by default for HTTP, true by default for HTTPS). Read more about this option below.
  • httpOnly: a boolean indicating whether the cookie is only to be sent over HTTP(S), and not made available to client JavaScript (true by default).
  • partitioned: a boolean indicating whether to partition the cookie in Chrome for the CHIPS Update (false by default). If this is true, Cookies from embedded sites will be partitioned and only readable from the same top level site from which it was created.
  • priority: a string indicating the cookie priority. This can be set to 'low', 'medium', or 'high'.
  • sameSite: a boolean or string indicating whether the cookie is a "same site" cookie (false by default). This can be set to 'strict', 'lax', 'none', or true (which maps to 'strict').
  • signed: a boolean indicating whether the cookie is to be signed (false by default). If this is true, another cookie of the same name with the .sig suffix appended will also be sent, with a 27-byte url-safe base64 SHA1 value representing the hash of cookie-name=cookie-value against the first Keygrip key. This signature key is used to detect tampering the next time a cookie is received.
  • overwrite: a boolean indicating whether to overwrite previously set cookies of the same name (false by default). If this is true, all cookies set during the same request with the same name (regardless of path or domain) are filtered out of the Set-Cookie header when setting this cookie.

Secure cookies

To send a secure cookie, you set a cookie with the secure: true option.

HTTPS is necessary for secure cookies. When cookies.set is called with secure: true and a secure connection is not detected, the cookie will not be set and an error will be thrown.

This module will test each request to see if it's secure by checking:

  • if the protocol property of the request is set to https, or
  • if the connection.encrypted property of the request is set to true.

If your server is running behind a proxy and you are using secure: true, you need to configure your server to read the request headers added by your proxy to determine whether the request is using a secure connection.

For more information about working behind proxies, consult the framework you are using:

If your Koa or Express server is properly configured, the protocol property of the request will be set to match the protocol reported by the proxy in the X-Forwarded-Proto header.

Example

var http = require('http')
var Cookies = require('cookies')

// Optionally define keys to sign cookie values
// to prevent client tampering
var keys = ['keyboard cat']

var server = http.createServer(function (req, res) {
  // Create a cookies object
  var cookies = new Cookies(req, res, { keys: keys })

  // Get a cookie
  var lastVisit = cookies.get('LastVisit', { signed: true })

  // Set the cookie to a value
  cookies.set('LastVisit', new Date().toISOString(), { signed: true })

  if (!lastVisit) {
    res.setHeader('Content-Type', 'text/plain')
    res.end('Welcome, first time visitor!')
  } else {
    res.setHeader('Content-Type', 'text/plain')
    res.end('Welcome back! Nothing much changed since your last visit at ' + lastVisit + '.')
  }
})

server.listen(3000, function () {
  console.log('Visit us at http://127.0.0.1:3000/ !')
})

License

MIT