Safe Stable Stringify

2.5.0 · active · verified Sun Apr 19

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.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates configuring `safe-stable-stringify` to handle circular references, BigInts, and ensure deterministic key order, then serializing an object with these features.

import { configure } from 'safe-stable-stringify';

const userObject = {
  id: 123,
  name: 'Alice',
  settings: {
    theme: 'dark',
    notifications: true,
    circularRef: null // Will be set later
  },
  roles: ['admin', 'user'],
  creationDate: new Date(),
  bigIntId: 9007199254740991123n // Example BigInt
};
userObject.settings.circularRef = userObject; // Create a circular reference

// Configure stringify for deterministic output, handling circular refs and BigInts
const stringify = configure({
  deterministic: true, // Sort object keys alphabetically
  circularValue: '[CIRCULAR_REF]', // Replace circular references with this string
  bigint: true, // Convert BigInts to numbers
  maximumDepth: 3 // Limit serialization depth
});

try {
  const serialized = stringify(userObject, null, 2);
  console.log(serialized);
  // Expected output (order of keys will be stable, BigInt converted):
  // {
  //   "bigIntId": 9007199254740991123,
  //   "creationDate": "2026-04-19T06:51:00.000Z", // Actual date will vary
  //   "id": 123,
  //   "name": "Alice",
  //   "roles": [
  //     "admin",
  //     "user"
  //   ],
  //   "settings": {
  //     "circularRef": "[CIRCULAR_REF]",
  //     "notifications": true,
  //     "theme": "dark"
  //   }
  // }
} catch (error) {
  console.error('Serialization error:', error.message);
}

view raw JSON →