{"id":11976,"library":"safe-stable-stringify","title":"Safe Stable Stringify","description":"safe-stable-stringify is a JavaScript utility that provides a deterministic and safe alternative to JSON.stringify. Currently at version 2.5.0, it offers consistent object key ordering, graceful handling of circular references, and configurable serialization of BigInt values, addressing common pitfalls of the native `JSON.stringify`. The library maintains a regular release cadence, frequently adding new options and performance improvements. Key differentiators include its configurable deterministic sorting using custom comparators, options to control maximum serialization depth and breadth, and the ability to define how circular references or BigInts are handled (e.g., replacement values, throwing errors, or omission). It ships with TypeScript types, supports both ESM and CommonJS modules, and has zero external dependencies, making it a robust choice for environments requiring reliable JSON serialization.","status":"active","version":"2.5.0","language":"javascript","source_language":"en","source_url":"https://github.com/BridgeAR/safe-stable-stringify","tags":["javascript","stable","stringify","JSON","JSON.stringify","safe","serialize","deterministic","circular","typescript"],"install":[{"cmd":"npm install safe-stable-stringify","lang":"bash","label":"npm"},{"cmd":"yarn add safe-stable-stringify","lang":"bash","label":"yarn"},{"cmd":"pnpm add safe-stable-stringify","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"For ESM, the primary `stringify` function is a named export. It offers default safe and deterministic behavior. For CJS, use `const stringify = require('safe-stable-stringify')`.","wrong":"import stringify from 'safe-stable-stringify'","symbol":"stringify","correct":"import { stringify } from 'safe-stable-stringify'"},{"note":"The `configure` function is a named export in ESM, used to create custom stringify functions with specific options (e.g., `circularValue`, `bigint`, `deterministic`). For CJS, it can be accessed via `const { configure } = require('safe-stable-stringify')`.","wrong":"import configure from 'safe-stable-stringify'","symbol":"configure","correct":"import { configure } from 'safe-stable-stringify'"},{"note":"In CommonJS environments, the main `stringify` function is the default export of the package. `configure` is available as a named property on this default export.","wrong":"const { stringify } = require('safe-stable-stringify')","symbol":"stringify (CJS)","correct":"const stringify = require('safe-stable-stringify')"}],"quickstart":{"code":"import { configure } from 'safe-stable-stringify';\n\nconst userObject = {\n  id: 123,\n  name: 'Alice',\n  settings: {\n    theme: 'dark',\n    notifications: true,\n    circularRef: null // Will be set later\n  },\n  roles: ['admin', 'user'],\n  creationDate: new Date(),\n  bigIntId: 9007199254740991123n // Example BigInt\n};\nuserObject.settings.circularRef = userObject; // Create a circular reference\n\n// Configure stringify for deterministic output, handling circular refs and BigInts\nconst stringify = configure({\n  deterministic: true, // Sort object keys alphabetically\n  circularValue: '[CIRCULAR_REF]', // Replace circular references with this string\n  bigint: true, // Convert BigInts to numbers\n  maximumDepth: 3 // Limit serialization depth\n});\n\ntry {\n  const serialized = stringify(userObject, null, 2);\n  console.log(serialized);\n  // Expected output (order of keys will be stable, BigInt converted):\n  // {\n  //   \"bigIntId\": 9007199254740991123,\n  //   \"creationDate\": \"2026-04-19T06:51:00.000Z\", // Actual date will vary\n  //   \"id\": 123,\n  //   \"name\": \"Alice\",\n  //   \"roles\": [\n  //     \"admin\",\n  //     \"user\"\n  //   ],\n  //   \"settings\": {\n  //     \"circularRef\": \"[CIRCULAR_REF]\",\n  //     \"notifications\": true,\n  //     \"theme\": \"dark\"\n  //   }\n  // }\n} catch (error) {\n  console.error('Serialization error:', error.message);\n}\n","lang":"typescript","description":"Demonstrates configuring `safe-stable-stringify` to handle circular references, BigInts, and ensure deterministic key order, then serializing an object with these features."},"warnings":[{"fix":"Review BigInt handling; if you need to ignore BigInts as in v1, set the `bigint` option to `false`. Ensure your environment supports ES6 and adapt imports for ESM if migrating from CJS.","message":"Version 2.0.0 introduced breaking changes including default BigInt conversion to number (previously ignored), required ES6 environment, and full ESM support.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"If non-deterministic (insertion order) serialization is desired, use `configure({ deterministic: false })`.","message":"The default behavior for object key order became deterministic (sorted keys) in v2.0.0. If you relied on insertion order, you need to explicitly set `deterministic: false`.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Avoid using boxed primitives if native `JSON.stringify` unboxing behavior is expected, or manually unbox them before serialization.","message":"Boxed primitives (e.g., `Number(5)`, `Boolean(true)`) are treated as regular objects and not unboxed, unlike native `JSON.stringify`. This can lead to different serialization outputs for these specific values.","severity":"gotcha","affected_versions":"all"},{"fix":"Ensure all values are JSON-compatible or explicitly configure `bigint` and `circularValue` options if they might be present. Handle `NaN`/`Infinity` or use custom replacers. Be aware that `strict` does not detect Sets, Maps, or Symbol keys as incompatible.","message":"Using the `strict` option verifies full JSON compatibility and will throw an error for non-JSON-compatible values (functions, `NaN`, `Infinity`), or if circular/BigInt values are present without explicit handling options. Sets, Maps, and Symbol keys are also not detected as incompatible.","severity":"gotcha","affected_versions":">=2.4.0"},{"fix":"Upgrade to `safe-stable-stringify` v2.3.1 or newer to resolve this issue. Ensure your environment supports modern RegExp features if staying on older versions.","message":"Earlier versions (prior to v2.3.1) could encounter 'invalid regexp group' errors in environments lacking negative lookbehind support for regular expressions (e.g., older browsers or Node.js versions).","severity":"gotcha","affected_versions":"<2.3.1"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Use `safe-stable-stringify` with the default `bigint: true` option (or explicitly set it), or provide a custom `replacer` function to handle BigInts. For `strict: true`, explicitly set `bigint: true` or `bigint: false` to ignore/convert.","cause":"Attempting to serialize a BigInt value using native `JSON.stringify`, or `safe-stable-stringify` with `bigint: false` and `strict: true`.","error":"TypeError: Do not know how to serialize a BigInt"},{"fix":"Configure `safe-stable-stringify` with `circularValue` set to a string (e.g., `'[Circular]'`), `null`, or `undefined` to handle circular references gracefully instead of throwing an error.","cause":"Attempting to serialize an object with circular references using native `JSON.stringify`, or `safe-stable-stringify` configured to throw on circular references (`circularValue: Error`).","error":"TypeError: Converting circular structure to JSON"}],"ecosystem":"npm"}