{"id":12307,"library":"universal-cookie","title":"Universal Cookie Management","description":"universal-cookie is a JavaScript library designed for isomorphic cookie management across diverse environments, including client-side browsers, Node.js servers, and integrated within React applications (often via the `react-cookie` wrapper). It provides a consistent API for setting, getting, and removing HTTP cookies, abstracting away the underlying environment specifics. The current stable version is `8.1.0`, with the project maintaining an active release cadence, regularly providing minor and patch updates, and recently introducing major version `8.0.0`. Its core value proposition lies in enabling developers to write single-codebase solutions for cookie handling, simplifying full-stack development by offering a unified approach to cookie lifecycle management, supporting standard cookie attributes like `path`, `expires`, `domain`, `secure`, `httpOnly`, and `sameSite`.","status":"active","version":"8.1.0","language":"javascript","source_language":"en","source_url":"https://github.com/ItsBenCodes/cookies","tags":["javascript","universal","isomophic","cookie","typescript"],"install":[{"cmd":"npm install universal-cookie","lang":"bash","label":"npm"},{"cmd":"yarn add universal-cookie","lang":"bash","label":"yarn"},{"cmd":"pnpm add universal-cookie","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The `Cookies` class is the default export. Using named import will result in `undefined` or a type error.","wrong":"import { Cookies } from 'universal-cookie';","symbol":"Cookies","correct":"import Cookies from 'universal-cookie';"},{"note":"When using CommonJS `require` to import a package with an ESM default export, `.default` is necessary to access the class constructor.","wrong":"const Cookies = require('universal-cookie');","symbol":"Cookies (CommonJS)","correct":"const Cookies = require('universal-cookie').default;"},{"note":"TypeScript types are included with the package and can be imported directly from the main module, ensuring correct type inference and tooling support.","wrong":"import { CookieSetOptions } from 'universal-cookie/types';","symbol":"Cookies (Type Import)","correct":"import type { CookieSetOptions, CookieGetOptions } from 'universal-cookie';"}],"quickstart":{"code":"import Cookies from 'universal-cookie';\n\ninterface MyCookieData {\n  username: string;\n  lastLogin: string;\n}\n\nconst cookies = new Cookies();\n\n// Set a cookie that expires in 1 hour\nconst expirationDate = new Date();\nexpirationDate.setTime(expirationDate.getTime() + 60 * 60 * 1000);\n\nconst userData: MyCookieData = {\n  username: 'checklist_agent',\n  lastLogin: new Date().toISOString()\n};\n\ncookies.set('user_session', JSON.stringify(userData), {\n  path: '/',\n  expires: expirationDate,\n  secure: process.env.NODE_ENV === 'production',\n  sameSite: 'lax' // Recommended for general use\n});\n\nconsole.log('Cookie set: user_session');\n\n// Get a cookie\nconst storedSession = cookies.get('user_session');\nif (storedSession) {\n  const parsedData: MyCookieData = JSON.parse(storedSession);\n  console.log('Retrieved user_session:', parsedData);\n} else {\n  console.log('user_session cookie not found.');\n}\n\n// Remove a cookie\n// cookies.remove('user_session', { path: '/' });\n// console.log('Cookie removed: user_session');","lang":"typescript","description":"Demonstrates initializing the Cookies class, setting a JSON stringified cookie with options like expiration and path, and retrieving it. Includes type definitions for clarity."},"warnings":[{"fix":"Ensure `httpOnly: true` is only used for server-side cookies. For client-side accessible data, omit the `httpOnly` option. Consider using secure, client-side only cookies for non-sensitive data, or rely on server-side logic to handle `httpOnly` cookies securely.","message":"Cookies marked `httpOnly` cannot be accessed, read, or modified by client-side JavaScript, including `universal-cookie`. This is a security feature to prevent XSS attacks. Attempting to get or set such cookies from the browser will fail silently or return undefined.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Update dependencies and re-run your build. If issues persist, check your `tsconfig.json` module resolution settings and ensure your bundler is correctly configured for ESM. Refer to the official changelog or GitHub issues for any specific migration guides related to module changes.","message":"When migrating to v8.0.0, developers should verify their module imports and TypeScript configurations. While specific core API breaking changes were not explicitly detailed in the changelog, major version bumps often involve updates to module resolution (e.g., `package.json` `exports` field) which can affect how bundlers and TypeScript interpret imports, especially in dual CommonJS/ESM setups. Past versions (e.g., v7.1.x) included fixes for TypeScript definitions and ESM compatibility.","severity":"breaking","affected_versions":">=8.0.0"},{"fix":"Always set `secure: true` when `sameSite: 'None'`. Ensure your application is served over HTTPS in production to support these cookie settings.","message":"When setting `sameSite: 'None'` for cross-site cookies, the `secure` option MUST also be set to `true`. Browsers will reject cookies that specify `SameSite=None` but are not sent over HTTPS. This is a critical security requirement imposed by modern browsers.","severity":"gotcha","affected_versions":">=4.0.2"},{"fix":"Ensure the `domain` option correctly reflects the current host or a valid subdomain. If cross-domain cookie sharing is required, consider alternative strategies like proxying requests or using server-side redirects with explicit cookie forwarding.","message":"Cookies can only be set for the current domain or its subdomains. Attempting to set a cookie for an unrelated or parent domain (e.g., setting a cookie for `example.com` from `sub.example.com` or for `another.com` from `example.com`) will cause the cookie to be silently rejected by the browser or server without being set.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure you instantiate the `Cookies` class with `new Cookies()`. If using `require` in CommonJS, use `const Cookies = require('universal-cookie').default;` to access the default export constructor.","cause":"Attempting to call `Cookies()` without `new` or incorrectly importing the default export in CommonJS environments.","error":"TypeError: Cookies is not a constructor"},{"fix":"Ensure `universal-cookie` is correctly installed. For older TypeScript versions or complex setups, verify `tsconfig.json` for `moduleResolution` (e.g., `bundler` or `node`). Ensure no conflicting `@types/universal-cookie` package is installed. This issue was specifically fixed in v7.0.1 for certain module configurations.","cause":"TypeScript compiler cannot find the type definitions for the `universal-cookie` package, often due to incorrect import paths, mismatched package versions, or tooling misconfiguration.","error":"Could not find a declaration file for module 'universal-cookie'."},{"fix":"When setting `sameSite: 'None'`, you must also set `secure: true` in the cookie options. This ensures the cookie is only sent over HTTPS, which is a requirement for cross-site cookies.","cause":"A browser warning indicating that a cookie is being set with `SameSite=None` but without the `Secure` attribute, violating modern browser security policies.","error":"Cookie \"your-cookie-name\" will be soon rejected because it has the \"SameSite\" attribute set to “None” or an invalid value, without the “secure” attribute. To learn more, see https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie/SameSite"},{"fix":"Review the `domain` option in your `set` call. It should be the current host or a specific subdomain of the current host. Cookies cannot be set for arbitrary domains.","cause":"Attempting to set a cookie with a `domain` option that is not valid for the current host (e.g., trying to set a cookie for a different top-level domain or a non-existent subdomain).","error":"This set-cookie was blocked because its domain attribute was invalid with regards to the current host URL."}],"ecosystem":"npm"}