Validate webhook payload types
Before parsing a webhook payload, verify that the request declares JSON and reject other media types.
Express.js · Module
req.is() checks whether the request Content-Type matches a MIME type or extension. It returns the matched type, false for a mismatch, or null when there is no body.
Call req.is(type) to test the incoming request's Content-Type against a MIME type or extension. It reports the matching type, false for a mismatch, and null when the request has no body.
req.is(type)| Name | Type | Description |
|---|---|---|
type | String | String[] | MIME type or extension name, or an array of MIME types and extension names, to compare with the request Content-Type. |
String | false | null
const express = require('express');
const app = express();
app.use(express.json());
app.post('/webhook', (req, res) => {
if (req.is('json')) {
return res.json({ accepted: true });
}
return res.status(415).send('Expected JSON');
});
app.listen(3000);The route accepts the request only when its Content-Type matches JSON; otherwise it returns 415.
Before parsing a webhook payload, verify that the request declares JSON and reject other media types.
Accept any subtype in a media family, such as text/*, when a route supports several textual formats.
Use a list of accepted MIME types or extensions for an endpoint supporting multiple representations.
req.is(type) compares the request’s Content-Type header with a MIME type or extension name. It returns the matching content type when successful, false on mismatch, and null when the request has no body.
Follow-up: How would you distinguish an empty-body request from an unsupported media type? Check for null first; treat false as an unsupported or nonmatching Content-Type.
The type argument can be a string or an array of strings. Each value represents a MIME type or extension name to compare with the request’s Content-Type.
Follow-up: Why might an extension such as json be convenient? Express can match that extension against the corresponding MIME type, avoiding a longer literal MIME string.
Use req.is('json') when a route expects JSON, or a wildcard such as req.is('text/*') when any text subtype is acceptable. A matching request produces the matching type string; a nonmatching one produces false.
Follow-up: What response is appropriate for a nonmatching type? Reject the payload with an unsupported-media-type response, commonly HTTP 415.
req.get()req.bodyreq.headersexpress.json()