DEV Community

Cover image for Parse POST/PATCH/PUT request JSON body with Express and no dependencies
Hugo Di Francesco
Hugo Di Francesco

Posted on • Originally published at codewithhugo.com on

Parse POST/PATCH/PUT request JSON body with Express and no dependencies

When asked to handle data in a request body, developers who have used Express (the “Fast, unopinionated, minimalist web framework for Node.js”) before, reach for the body-parser library.

The same functionality can be achieved using express.json(). A middleware for parsing JSON request bodies built-into Express.

Note: express.json exists only in Express 4.16+

Here is an example app that reflects the request POST body in the response:

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

app.use(express.json())
app.post(
  '/test',
  (req, res) => res.json(req.body)
)

const PORT = process.env.PORT || 3000
app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`)
})

You can see it running at https://olrn6x3n19.sse.codesandbox.io/, test it using:

curl --request POST \
  --url https://olrn6x3n19.sse.codesandbox.io/test \
  --header 'content-type: application/json' \
  --data '{
    "json-parsing": "just with Express",
    "no": "body-parser"
}'

It will output:

{"json-parsing":"just with Express","no":"body-parser"}

Which is exactly what we sent in the --data property of the curl request.

You can pass options into it like so (all the values are the default values for these options):

app.use(express.json({
  inflate: true,
  limit: '100kb',
  reviver: null,
  strict: true,
  type: 'application/json',
  verify: undefined
}))

The full API docs for express.json are at expressjs.com/en/api.html#express.json.

A run-through of the options follows.

inflate controls whether or not to handle compressed/deflated request bodies. When it’s set to false, compressed/deflated bodies will get rejected.

limit controls the maximum body size. It can be either a number of bytes or a string which is compatible with the bytes library.

strict is about locking JSON.parse down to just objects and arrays. If true, only JSON.stringify-ed objects and arrays will be allowed, if false, anything that JSON.parse accepts will be parsed.

type controls which content-type the middleware will attempt to parse. The value for this option can be a string, an array of strings, or a function. Content-type wildcards are supported to some extent since string(s) are passed to the type-is library.

verify is an optional function with verify(req, res, buf, encoding) signature. buf is a Buffer containing the raw request body. verify can be used to abort parsing by throwing an error.

Despite not being necessary for parsing JSON bodies, body-parser remains a great library that provides parsers for other body types (see the docs at github.com/expressjs/body-parser):

The exception is multipart bodies, there are alternative libraries to handle that use-case (usually for file upload).

unsplash-logo
Mahir Uysal

Top comments (0)