Node js What Does [Object: null prototype] Mean

The output [Object: null prototype] { adf: 'bsdf' } appears in the console when you log req.body in your Express.js application because of how the body-parser middleware processes incoming JSON data.

What Does [Object: null prototype] Mean?

The notation [Object: null prototype] indicates that the object being logged is a plain object created with a null prototype. In JavaScript, objects usually have a prototype, typically Object.prototype, which provides access to built-in methods like toString, hasOwnProperty, etc.

When you see [Object: null prototype], it means that the object was created in a way that deliberately sets its prototype to null. This kind of object doesn’t inherit from Object.prototype, so it lacks the standard methods and properties that you would expect from a regular JavaScript object.

Why Is This Happening?

This behavior occurs because of how body-parser parses URL-encoded data and JSON data. When body-parser is used to parse incoming request bodies, it may create objects with a null prototype for security reasons. This is done to avoid potential security issues related to prototype pollution, which can occur if someone tries to tamper with an object’s prototype chain.

Here’s what happens in your code:

  1. POST Request: When a POST request is made to your server, body-parser processes the request body.
  2. Object Creation: If the incoming data is JSON or URL-encoded data, body-parser may create an object with a null prototype to store the parsed data.
  3. Console Log: When you log req.body, the console output shows [Object: null prototype] { adf: 'bsdf' }, indicating that req.body is an object with a null prototype, containing the key-value pair adf: 'bsdf'.

How to Work with This Object

Even though the object has a null prototype, you can still access its properties in the usual way. For example, you can access req.body.adf just as you would with a regular object.

If you need to create a regular object from this, you can do so by using Object.assign or the spread operator:

const regularObject = { ...req.body };

Or:

const regularObject = Object.assign({}, req.body);

This will give you a regular object that no longer has a null prototype.

Conclusion

The [Object: null prototype] output in the console is a result of body-parser‘s design to mitigate security risks like prototype pollution. The object itself behaves like a regular JavaScript object for most practical purposes, but it lacks the prototype chain associated with Object.prototype. You can safely work with this object as you normally would, or convert it to a regular object if necessary.