I am using request package for node.js
Code :
var formData = ({first_name:firstname,last_name:lastname,user_name:username, email:email,password:password});
request.post({url:'http://localhost:8081/register', JSON: formData}, function(err, connection, body) {
exports.Register = function(req, res) {
res.header("Access-Control-Allow-Origin", "*");
console.log("Request data " +JSON.stringify(req));
Here I am getting this error :
TypeError: Converting circular structure to JSON
Can anybody tell me what is the problem
![]()
Rohìt Jíndal
23.9k12 gold badges70 silver badges119 bronze badges
asked Nov 24, 2014 at 9:11
Hitu BansalHitu Bansal
2,78910 gold badges50 silver badges87 bronze badges
3
JSON doesn’t accept circular objects — objects which reference themselves. JSON.stringify() will throw an error if it comes across one of these.
The request (req) object is circular by nature — Node does that.
In this case, because you just need to log it to the console, you can use the console’s native stringifying and avoid using JSON:
console.log("Request data:");
console.log(req);
answered Nov 24, 2014 at 9:25
7
I also ran into this issue. It was because I forgot to await for a promise.
answered May 8, 2020 at 11:13
SatyaSatya
1,3538 silver badges13 bronze badges
0
Try using this npm package. This helped me decoding the res structure from my node while using passport-azure-ad for integrating login using Microsoft account
https://www.npmjs.com/package/circular-json
You can stringify your circular structure by doing:
const str = CircularJSON.stringify(obj);
then you can convert it onto JSON using JSON parser
JSON.parse(str)
answered Nov 6, 2019 at 6:46
![]()
2
I was able to get the values using this method, found at careerkarma.com
Output looks like this.

I just run this code in the debugger console. Pass your object to this function.
Copy paste the function also.
const replacerFunc = () => {
const visited = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (visited.has(value)) {
return;
}
visited.add(value);
}
return value;
};
};
JSON.stringify(circObj, replacerFunc());
answered Nov 8, 2021 at 9:12
![]()
Arun Prasad E SArun Prasad E S
9,1198 gold badges73 silver badges84 bronze badges
I forgotten to use await keyword in async function.
with the given systax
blogRouter.put('/:id', async (request, response) => {
const updatedBlog = Blog.findByIdAndUpdate(
request.params.id,
request.body,
{ new: true }
);
response.status(201).json(updatedBlog);
});
Blog.findByIdAndUpdate should be used with the await keyword.
answered May 23, 2021 at 5:19
![]()
use this https://www.npmjs.com/package/json-stringify-safe
var stringify = require('json-stringify-safe');
var circularObj = {};
circularObj.circularRef = circularObj;
circularObj.list = [ circularObj, circularObj ];
console.log(stringify(circularObj, null, 2));
stringify(obj, serializer, indent, decycler)
answered May 30, 2020 at 13:32
Mohit GuptaMohit Gupta
1931 silver badge12 bronze badges
1
It’s because you don’t an async response For example:
app.get(`${api}/users`, async (req, res) => {
const users = await User.find()
res.send(users);
})
![]()
SherylHohman
15.7k17 gold badges87 silver badges90 bronze badges
answered Feb 12, 2021 at 15:59
3
This is because JavaScript structures that include circular references can’t be serialized with a»plain» JSON.stringify.
https://www.npmjs.com/package/circular-json mentioned by @Dinesh is a good solution. But this npm package has been deprecated.
So use https://www.npmjs.com/package/flatted npm package directly from the creator of CircularJSON.
Simple usage. In your case, code as follows
import package
// ESM
import {parse, stringify} from 'flatted';
// CJS
const {parse, stringify} = require('flatted');
and
console.log("Request data " + stringify(req));
answered May 10, 2021 at 14:45
![]()
Pankaj ShindePankaj Shinde
3,1732 gold badges35 silver badges43 bronze badges
1
If you are sending reponse , Just use await before response
await res.json({data: req.data});
answered Mar 22, 2021 at 12:58
![]()
0
Came across this issue in my Node Api call when I missed to use await keyword in a async method in front of call returning Promise. I solved it by adding await keyword.
answered Dec 18, 2020 at 16:03
I was also getting the same error, in my case it was just because of not using await with Users.findById() which returns promise, so response.status().send()/response.send() was getting called before promise is settled (fulfilled or rejected)
Code Snippet
app.get(`${ROUTES.USERS}/:id`, async (request, response) => {
const _id = request.params.id;
try {
// was getting error when not used await
const user = await User.findById(_id);
if (!user) {
response.status(HTTP_STATUS_CODES.NOT_FOUND).send('no user found');
} else {
response.send(user);
}
} catch (e) {
response
.status(HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR)
.send('Something went wrong, try again after some time.');
}
});
Ryan M♦
17.3k30 gold badges60 silver badges70 bronze badges
answered Apr 23, 2022 at 17:31
![]()
WasitShafiWasitShafi
6391 gold badge7 silver badges12 bronze badges
2
I came across this issue when not using async/await on a asynchronous function (api call). Hence adding them / using the promise handlers properly cleared the error.
answered Jun 13, 2020 at 5:58
Sasi Kumar MSasi Kumar M
2,3021 gold badge22 silver badges23 bronze badges
For mongodb
so if you are getting errors while fetching data from MongoDB then the problem is async
previously

app.get('/users',(req,res,next)=>{
const user=chatUser.find({});
if(!user){
res.status(404).send({message:"there are no users"});
}
if(user){
res.json(user);
}
})
After
app.get('/users',async(req,res,next)=>{
const user=await chatUser.find({});
if(!user){
res.status(404).send({message:"there are no users"});
}
if(user){
res.json(user);
}
})
answered Jan 16 at 11:46
![]()
I had a similar issue:-
const SampleFunction = async (resp,action) => {
try{
if(resp?.length > 0) {
let tempPolicy = JSON.parse(JSON.stringify(resp[0]));
do something
}
}catch(error){
console.error(«consoleLogs.Utilities.XXX.YYY», error);
throw error;
}
.
.
I put await before JSON.parse(JSON.stringify(resp[0])).
This was required in my case as otherwise object was read only.
Both Object.create(resp[0]) and {…resp[0]} didn’t suffice my need.
answered Apr 26, 2022 at 12:24
![]()
1

If an object has a different type of property like mentioned in the above image, JSON.stringify() will through an error.
answered Nov 23, 2022 at 8:45
![]()
1
Try this as well
console.log(JSON.parse(JSON.stringify(req.body)));
![]()
answered Jun 12, 2021 at 5:34
2
TypeError: Converting circular structure to JSON in nodejs:
This error can be seen on Arangodb when using it with Node.js, because storage is missing in your database. If the archive is created under your database, check in the Aurangobi web interface.
![]()
answered Dec 18, 2019 at 10:43
The Javascript error “TypeError: Converting circular structure to JSON” happens when you try to stringify a Javascript object that contains a reference to itself. Fix this by either removing the circular reference or by using a 3rd party library to stringify the object.
Javascript comes with a lot of cool built-in stuff. One thing of particular usefulness is the JSON group of functions, specifically JSON.stringify(). It allows you to take almost any Javascript object and turn it into a string representation of itself. That string representation is called JSON, or “Javascript Object Notation”, and is one of the most, if not the most popular data serialization formats in use on the web today.
Unfortunately, however, it can’t do everything. I said “almost” any Javascript object for a reason – if you try to serialize an object that contains a reference to itself, JSON.stringify() will explode. Well, it won’t explode, but it’ll barf out a nasty looking error message for you.
Here’s an example of exactly that:
const foo = {};
foo.bar = "baz";
foo.thing = foo;
console.log(JSON.stringify(foo));
Seems innocent enough, right? All we did was created an object called foo, assigned a member called bar the value of baz, then added another property called thing, and assigned it the value of… foo. You can do that, right? Wrong.
If you try to do this, you’ll get the following verbose (but helpful) error:
/home/user/main.js:5
console.log(JSON.stringify(foo));
^
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Object'
--- property 'thing' closes the circle
at JSON.stringify (<anonymous>)
at Object.<anonymous> (/home/user/main.js:5:18)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
Woah! What’s all that mean? Well, what it’s complaining about is, the object contains a reference to itself. In programming, this is what’s known as a “circular reference”. It’s called that since, if you were to draw out the dependency tree on paper, it would make a circle. Hence, circular reference. Make sense?
Now, how do we fix this problem? Granted, our example above is contrived and extremely simple. In real life, you’ll probably have no idea where the circular reference is. We’ll get to how to handle that a bit later. But first, let’s look at what to do if you’re reasonably sure you know where the problem is.
Fix 1: remove the circular reference
Again, this one is easy, and is only suited for situations where you know exactly where the problem lies. In our example, the problem is on the highlighted line below:
const foo = {};
foo.bar = "baz";
foo.thing = foo;
console.log(JSON.stringify(foo));
That’s the place where we’re introducing the circular reference. What we’re doing is, we’re assigning the thing property of the foo object a reference to… the foo object. You can see how this would be a problem. The JSON.stringify() method gets to this, and ends up doing infinite recursion. If you remember back to your intro to programming class, this is a problem.
So how do we fix this? I don’t want to blow your mind, but I might have to: we’re going to just not do that. That’s right. We’re just going to not do the thing that is causing the problem. Observe:
const foo = {};
foo.bar = "baz";
console.log(JSON.stringify(foo));
// => {"bar":"baz"}
Ta-da! I know, I know. If it were that simple, you’d have done it already.
Let’s now look at a couple solutions that will be more useful for a more complicated scenario.
Fix 2: use the flatted package
If you’re in a situation where you’re getting the “TypeError: Converting circular structure to JSON” error and you’re not sure where it’s originating, chill out. It’s (current year) and someone has already solved this problem for you. All you have to do is use their solution instead.
The first 3rd party solution we’ll look at is the flatted package. You can install it with the following command:
Once installed, we can add it to our example like so:
const { stringify } = require('flatted');
const foo = {};
foo.bar = "baz";
foo.thing = foo;
console.log(stringify(foo));
// => [{"bar":"1","thing":"0"},"baz"]
What we did here is we imported the stringify function from flatted and used it instead of the JSON.stringify() function. Flatted’s implementation knows how to handle infinite recursion. As you can see, the output is… a little weird. It took the foo object and turned it into an array.
Essentially, this is what’s happening: the first element {"bar":"1", "thing":"0"} is an object that represents the foo object. But, each property is instead the index of the thing it references within the outer array object. This allows for circular references. Since our “thing” property was the offending circular reference, you can see the index it’s referencing is 0, which is the index of the foo object representation. Hence, our circular reference is “flattened” out (or “flatted” if you will).
This output may not work directly with your application, since it’s weird. You’ll have to adjust the code that uses the JSON representation to work with this new format, if you choose to use it.
Fix 3: use the @ungap/structured-clone/json pacakge
Next up we have the npm package @ungap/structured-clone. It’s got a lot of other stuff in there, but the thing we’re interested in is the stringify function located within @ungap/structured-clone/json. We can install it with the following npm command:
npm install @ungap/structured-clone
Once installed, we can import it into our example and use it like this:
const { stringify } = require('@ungap/structured-clone/json');
const foo = {};
foo.bar = "baz";
foo.thing = foo;
console.log(stringify(foo));
// => [[2,[[1,2],[3,0]]],[0,"bar"],[0,"baz"],[0,"thing"]]
Spoiler alert: I have no idea how to make sense of the output. I don’t use this package, so if you want to figure out why it looks like that and how to use it,
We’re seeing this issue but, extending the above example, it’s the err.request._currentRequest._redirectable which is a circular reference.
request: Writable { ... _currentRequest: ClientRequest { domain: null, _events: [Object], _eventsCount: 6, _maxListeners: undefined, output: [], outputEncodings: [], outputCallbacks: [], outputSize: 0, writable: true, _last: true, upgrading: false, chunkedEncoding: false, shouldKeepAlive: false, useChunkedEncodingByDefault: true, sendDate: false, _removedHeader: [Object], _contentLength: null, _hasBody: true, _trailer: '', finished: false, _headerSent: true, socket: [Object], connection: [Object], _header: '...', _headers: [Object], _headerNames: [Object], _onPendingData: null, agent: [Object], socketPath: undefined, timeout: undefined, method: 'POST', path: '...', _ended: false, _redirectable: [Circular], // <---- parser: null }, _currentUrl: '...' }, response: undefined }
The JavaScript exception «cyclic object value» occurs when object references were found
in JSON. JSON.stringify() doesn’t try
to solve them and fails accordingly.
Message
TypeError: Converting circular structure to JSON (V8-based) TypeError: cyclic object value (Firefox) TypeError: JSON.stringify cannot serialize cyclic structures. (Safari)
Error type
What went wrong?
The JSON format per se doesn’t support object
references (although an IETF draft exists),
hence JSON.stringify() doesn’t try to solve them and fails accordingly.
Examples
Circular references
In a circular structure like the following
const circularReference = {otherData: 123};
circularReference.myself = circularReference;
JSON.stringify() will fail
JSON.stringify(circularReference);
// TypeError: cyclic object value
To serialize circular references you can use a library that supports them (e.g. cycle.js)
or implement a solution by yourself, which will require finding and replacing (or
removing) the cyclic references by serializable values.
The snippet below illustrates how to find and filter (thus causing data loss) a cyclic
reference by using the replacer parameter of
JSON.stringify():
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
JSON.stringify(circularReference, getCircularReplacer());
// {"otherData":123}
See also
JSON.stringify-
cycle.js
– Introduces two functions,JSON.decycleand
JSON.retrocycle, which makes it possible to encode and decode cyclical
structures and dags into an extended and retrocompatible JSON format.
When we send an object containing circular references to the JSON.stringify() function, we get the TypeError: Converting circular structure to JSON problem. Before converting the object to JSON, avoid any circular reference.
Fix TypeError: Converting circular structure to JSON in JavaScript
This issue can be solved using the flatted package. The flatted package is a Circular JSON parser that is incredibly light and quick, directly from the inventor of CircularJSON.
First, you have to install a flatted package, and you can do it the following way.
npm i flatted
Let’s see one example of using a flatted package.
const { parse, stringify } = require("flatted/cjs");
var sports = [{ cricket: 1 }, { football: "2" }];
sports[0].a = sports;
stringify(sports);
console.log(sports);
Output:

JSON.stringify() not only turns valid objects into strings but also has a replacer parameter that may replace values if the function is configured.
let sportsmanObj = {
name: "Shiv",
age: 22,
gender: "Male",
};
sportsmanObj.myself = sportsmanObj;
const circularFunc = () => {
const sited = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (sited.has(value)) {
return;
}
sited.add(value);
}
return value;
};
};
JSON.stringify(sportsmanObj, circularFunc());
console.log(sportsmanObj);
Run Code
We are calling on the WeakSet object in our circularFunc above, which is an object that stores weakly held items or pointers to things.
Each object in a WeakSet can only appear once, removing repetitive or circular data. The new keyword is an operator for creating a new object.
We have nested if statements in our return statement. The typeof operator is used in our first if statement to return the primitive (Undefined, Null, Boolean, Number, String, Function, BigInt, Symbol) being evaluated.
If our type of value is precisely equivalent to an object and the importance of that object is not null, it will proceed to the second if condition, which will check to see if the value is in the WeakSet(). We send our original circular structure and replacer method to JSON.stringify().
This will give us the stringified result we want on the console.
{
age: 22,
gender: "Male",
myself: [circular object Object],
name: "Shiv"
}