What Does `app.use(express.json())` Do in Express?

Dec 20, 2021

The app.use() function adds a new middleware to the app. Essentially, whenever a request hits your backend, Express will execute the functions you passed to app.use() in order. For example, if you wanted to print the HTTP method and the URL of every request, you would do the following:

const app = require('express')();

app.use((req, res, next) => {
  // For example, a GET request to `/test` will print "GET /test"
  console.log(`${req.method} ${req.url}`);

  next();
});

app.get('/test', (req, res, next) => {
  res.send('ok');
});

// Test the above app using Axios
const server = await app.listen(3000);

const axios = require('axios');
// Prints "get /test"
await axios.get('http://localhost:3000/test');

Using express.json()

express.json() is a built in middleware function in Express starting from v4.16.0. It parses incoming JSON requests and puts the parsed data in req.body.

const express = require('express');
const app = express();

app.use(express.json());

app.post('/test', function(req,res) {
  // Without `express.json()`, `req.body` is undefined.
  console.log(`${req.body}`);
});

// Test the above app using Axios
const server = await app.listen(3000);

const axios = require('axios');
// Prints "{ answer: 42 }"
await axios.post('http://localhost:3000/test', { answer: 42 });

Using the limit option in express.json()

The limit option allows you to specify the size of the request body. Whether you input a string or a number, it will be interpreted as the maximum size of the payload in bytes.

app.use(express.json({ limit: 10 }));
const app = require('express')();
app.use(express.json({ limit: 1 }));

app.post('/limit-break', (req, res, next) => {
  console.log(req.body);
  res.send('ok');
});

// Test the above app using Axios
const server = await app.listen(3000);

const axios = require('axios');
// Throws `PayloadTooLargeError: request entity too large`
const res = await axios.post('http://localhost:3000/limit-break', {
  name: 'Mastering JS',
  location: 'Florida',
  helpful: true
});

Built an Express app and want to deploy it?

We recommend Railway. It lets you deploy Node.js and Express apps without dealing with servers, Docker, CI/CD pipelines, or infrastructure. Click button, select GitHub repo, get URL. We've been using Railway for years to spin up apps quickly.

Deploy your Express app on Railway in minutes

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Express Tutorials