JSON.stringify() throws a TypeError when the object graph contains a circular reference, meaning an object refers back to itself (directly or indirectly). JSON is a tree format and cannot represent cycles.
Why it happens
- •An object has a property that points back to itself or to an ancestor in the graph.
- •DOM nodes often have circular references (parentNode, ownerDocument).
- •Express request/response objects contain circular references.
- •A data model with bidirectional relationships (parent referencing child and child referencing parent).
Examples
Code that triggers the error
const a = {};
const b = { ref: a };
a.ref = b; // circular
JSON.stringify(a);Error output
TypeError: Converting circular structure to JSON
How to fix it
Use a replacer function in JSON.stringify() to detect and break cycles. Libraries like flatted or json-stringify-safe handle circular references automatically. Consider using structuredClone() for deep copying instead of JSON round-tripping.
Fixed code
function safeStringify(obj) {
const seen = new WeakSet();
return JSON.stringify(obj, (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) return "[Circular]";
seen.add(value);
}
return value;
});
}Related errors
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free