How express.json() Works Under The Hood

How express.json() Works Under The Hood

Post by: Niraj Dhungana

Posted on: Nov 13, 2021

#JavaScript# Express# Node JS

It is always a nice thing to know how the code works before we write them. We all know (I hope) what express.json() middleware function does when we use it inside app.use() inside node express app. But there are a bunch of people who don't know how exactly it works.

BTW if you don’t know, then we use the express.json() method to convert a chunk or buffer data into a plain object. Let’s see what it means and how it works. If you want to know more about buffer data then here is a great post about buffer.

If we use express.json() then it adds the incoming data directly inside the req.body object. So, first let’s see how we can get the incoming data if we don't use express.json().

1
2
3
4
5
6
7
8
9
10
11
const express = require('express');
const app = express();

app.post("/create-post", (req, res, next) => {
    req.on("data", (chunk) => {
      req.body = JSON.parse(chunk);
      next();
    });
  }, (req, res) => {
    res.send(req.body);
  });

Here inside this code we are using a plain simple middleware function instead of express.json() method. If you guys don’t know about middleware functions then it might be a little hard to grasp things.

If I explain middleware functions in a single line. Then it’s a function which sits in the middle and runs before the actual logic if we call the next funcion.

Now because middleware functions run before the actual logic so we can access the incoming data before it moves to the next or main logic.

That is why here we are attaching the on listener to the req and listening to the data. If we do this then we will get the chunk data inside the callback function of the req.on() listener.

1
2
3
4
5
6
(req, res, next) => {
    req.on("data", (chunk) => {
      req.body = JSON.parse(chunk);
      next();
    });
}

This chunk is the buffer data which is coming from the frontend. Now because it is a buffer data we need to pass it through JSON.parse() method to convert into a plain object. If you want to you can console.log(chunk) to see how it looks.

After converting the chunk to the plain object. We are assigning it to the req.body so that we can use it in the next or our main logic. And calling the next function finally to move this logic to the next function.

So, guys this is how the express.json() method converts our chunk or buffer data into plain readable object data. It does more than this but it’s a simplified version to explain.