http-json-body-parser
This middleware automatically parses HTTP requests with a JSON body and converts the body into an
object. Broken or malformed JSON is handled gracefully as an Unprocessable Entity (422 error),
while a non-JSON Content-Type is reported as Unsupported Media Type (415 error),
if used in combination with httpErrorHandler.
For safety, a body carrying a prototype-pollution payload at any depth is rejected as an Unprocessable Entity (422 error) rather than parsed, so a malicious payload cannot mutate a
prototype in a downstream consumer. Detection follows the exploit structure: an own __proto__ key,
or a constructor key whose value contains a prototype member. Every other shape is preserved as
legitimate data, including a standalone prototype key or a constructor value that does not itself
contain a prototype.
It can also be used in combination with validator as a prior step to normalize the event body input as an object so that the content can be validated.
Install
To install this middleware you can use NPM:
npm install --save @middy/http-json-body-parser Options
reviver(function) (optional): A reviver parameter may be passed which will be usedJSON.parseing the body.disableContentTypeCheck(boolean) (optional): SkipContent-Typecheck for JSON. Default:false.disableContentTypeError(boolean) (optional): Skip throwing 415 whenContent-Typeis invalid. Default:false.
Sample usage
import middy from '@middy/core'
import httpHeaderNormalizer from '@middy/http-header-normalizer'
import httpJsonBodyParser from '@middy/http-json-body-parser'
const lambdaHandler = (event, context) => {
return {}
}
export const handler = middy()
.use(httpHeaderNormalizer())
.use(httpJsonBodyParser())
.handler(lambdaHandler)
// invokes the handler
const event = {
headers: {
'Content-Type': 'application/json'
// It is important that the request has the proper content type.
},
body: JSON.stringify({ foo: 'bar' })
}
handler(event, {}, (_, body) => {
deepStrictEqual(body, { foo: 'bar' })
}) Pairs well with
@middy/http-header-normalizer- register before this middleware so the Content-Type check sees lowercase keys.@middy/validator- register after so it can validate the parsed object.@middy/http-error-handler- maps the thrown 415 / 422 errors to a clean HTTP response.
See also
@middy/http-urlencode-body-parser- forapplication/x-www-form-urlencodedbodies.@middy/http-multipart-body-parser- formultipart/form-data(file uploads).@middy/ws-json-body-parser- for WebSocket payloads.- CORS and error handling recipe.
Last updated: