serialize-error
Serialize and deserialize JavaScript Error objects into plain, JSON-safe objects and back.
Repository Health
Technical Analysis
serialize-error is a small, dependency-light utility from the Sindre Sorhus ecosystem that converts JavaScript Error objects into plain objects safe for JSON.stringify() or process.send(), then converts them back into proper Error instances (including native subclasses like TypeError, RangeError, or DOMException) on the other side. It handles the edge cases that make errors awkward to move across process, worker, or network boundaries: non-enumerable properties like name, message, and stack are preserved as such, circular references are detected and replaced with a [Circular] marker, Buffer and Stream values are stringified instead of dumped, and non-Error values thrown by mistake are wrapped in a NonError instance so serialization never throws.
Beyond the basic round trip, it ships a registry of known error constructors that can be extended at runtime via addKnownErrorConstructor(), so custom Error subclasses retain their identity through serialization even when serialize-error is a transitive dependency rather than a direct one. A maxDepth option bounds recursion for deeply nested error graphs, and a useToJSON option lets consumers opt out of a value’s own .toJSON() method when they’d rather have serialize-error walk the object itself.
What You Get
- Two focused functions — serializeError() and deserializeError() — plus the isErrorLike() predicate, with no other public API surface to learn.
- Full TypeScript type definitions (ErrorObject, ErrorLike, Options) shipped alongside the JS and validated with tsd.
- A registry of native error constructors (Error, TypeError, RangeError, DOMException, Node’s AssertionError/SystemError, etc.) restored automatically on deserialization.
- addKnownErrorConstructor() for registering your own custom Error subclasses globally, with an optional factory for constructors that require arguments.
- Automatic wrapping of non-Error throws (strings, numbers, functions, undefined) in a NonError instance so serialization never throws on unexpected input.
Common Use Cases
- Passing errors across a Node.js child_process or cluster IPC boundary via process.send().
- Logging caught exceptions to JSON-based log pipelines (Pino, Winston, cloud log aggregators) without losing stack traces or custom properties.
- Serializing errors thrown inside Web Workers or iframes for postMessage() transport back to the main thread.
- Normalizing whatever a catch block receives — including non-Error throws — into a safe, loggable shape.
Under The Hood
Architecture The library centers on one recursive function, destroyCircular(), shared by both serializeError() and deserializeError() and parameterized by a serialize flag that switches its behavior between JSON-safe encoding and Error-instance reconstruction. A seen Set tracks in-progress objects to detect and mark circular references, while a module-level toJsonWasCalled WeakSet guards against re-entrant .toJSON() calls. Error-constructor identity is resolved separately, through error-constructors.js’s Map-based registry (errorConstructors, errorFactories), populated at import time from native globals (Error, TypeError, DOMException, Node’s AssertionError/SystemError, etc.) and extendable at runtime via addKnownErrorConstructor(). There are no classes or dependency injection — just two small ES modules and a handful of module-level Maps/WeakSets — but the bidirectional reuse of one recursive walker for both serialize and deserialize paths is a deliberate, tidy design choice for a package this size.
Tech Stack Pure ESM (“type”: “module”), targeting Node >=20, with zero runtime dependencies beyond non-error (a tiny Error-wrapping helper) and type-fest (used only for the JsonObject type). The package ships raw source directly via its exports field (index.js / index.d.ts) with no bundler or build step. Testing runs on ava (test.js, ~920 lines), linting on xo (Sindre Sorhus’s shared strict ESLint/style preset), and type correctness on tsd plus expect-type (index.test-d.ts). GitHub Actions workflows are present under .github/workflows for CI.
Code Quality test.js is extensive for a package this size, covering circular-reference destruction, non-enumerable property preservation, Buffer/Stream substitution, bigint handling, maxDepth truncation, toJSON override behavior, and multiple misuse paths for addKnownErrorConstructor (non-function factories, factories that throw, duplicate constructor names). Style is enforced by xo rather than a custom ESLint config, and public types are validated independently via tsd/expect-type rather than relying on the implementation file’s own (untyped) JS. No obvious gaps in error-path coverage were found; this is a well-tested small module.
What Makes It Unique Error serialization itself is a well-covered problem with several existing alternatives, so this isn’t a novel category of tool. What stands out is the care taken with fidelity: non-enumerable properties are kept non-enumerable on the way out and back in, an extensible constructor registry lets consumers preserve custom Error subclass identity even as a transitive dependency, and a factory-based registration path handles constructors that require arguments at construction time — a detail simpler serializers skip entirely.
Used by 8 apps in this directory
Budibase
Low Code Platforms · No Code Platforms
Build AI agents, automations, and internal apps on a single open-source platform with full self-hosting control.
Cline
AI Code Assistants
An open-source AI coding agent that lives in your editor and terminal — reads and edits your codebase, runs commands, browses the web, and requires human approval for every action by default.
HyperDX
Developer Tools · Analytics · Monitoring
Open source observability platform that unifies logs, traces, metrics, and session replays on ClickHouse — now the core of ClickStack.
Mattermost
Team Chat · Collaboration · Devops
Open core, self-hosted team collaboration with chat, AI agents, voice calling, and deep DevOps integrations — all under your control.
nango
Developer Tools · Automation · Authentication
Build product integrations with AI using 800+ APIs — auth, proxy, and TypeScript functions on production-grade infrastructure.
swagger-ui
Developer Tools
Transform OpenAPI specifications into interactive, browser-based API documentation that developers and consumers can explore and test live.
Umami
Analytics
Privacy-first web analytics that respects your users — self-hosted, cookieless, and GDPR compliant out of the box.
Webiny JS
Ecommerce · Blogging · CMS
Open-source, self-hosted CMS on AWS serverless — a TypeScript framework you extend with code, not a product you configure through a UI.