24 October 2026
Body Parser in TypeScript: Choose and Configure JSON and Form Parsing

TL;DR
A body parser turns an incoming HTTP request body into a value a handler can inspect. Choose it by the endpoint's accepted Content-Type, put it before input validation, and set limits. JSON, URL-encoded forms, text, raw bytes, and multipart uploads do not all take the same path. Parsing alone never makes data valid or a write authorized.
An API can look perfectly typed while accepting a body it cannot interpret. A client sends {"title":"Plan"} to a route expecting JSON, but omits Content-Type; the JSON middleware skips it and req.body is missing. Another client sends priority=2 as a form; the result is text, even if the application wants a number. I treat those as request-contract decisions, not mysterious TypeScript failures. Node's HTTP layer exposes the incoming message and stream without decoding an application's JSON or form format, while Express populates req.body only when the appropriate middleware runs. Node.js HTTP documentation and Express 5 request documentation explain those boundaries.
This guide concentrates on choosing and configuring parsing for particular routes. For a broader conceptual introduction and a Fastify example, read our bodyparser explainer. Here I use Express 5 for the HTTP adapter and db3.ai's documented validation function after parsing; this does not imply that db3.ai provides an Express body-parser service.
Table of contents
- What does a body parser actually do?
- Choose the parser from the route's accepted representation
- A TypeScript example with separate JSON and form routes
- What should happen when parsing fails?
- Frequently asked questions
- Sources
- Recommended Reads
What does a body parser actually do?
An HTTP request has headers and, potentially, a body of incoming bytes. A body parser reads that body, applies the format's decoding rules, and exposes a JavaScript value to subsequent middleware or a handler. In Express, JSON and URL-encoded parsers can populate req.body, while text and raw parsers produce a string and Buffer respectively. A parser does not decide whether title belongs to the request, whether a number falls inside a product rule, or whether the sender may change somebody else's record. Express 5 parser documentation distinguishes each parser's result; db3.ai's validation guide keeps conversion and authorization separate from validation.
The order is deliberate: select and bound a representation, parse it, validate the resulting value at runtime, then enforce identity and permissions before any side effect. In Express, middleware executes as part of the request-response chain, so registering a handler before its parser leaves the handler without that parser's result. You can register a parser for a particular route instead of applying every parser to the entire application. Express's middleware guide documents route-level middleware and execution order.
Choose the parser from the route's accepted representation
Content-Type describes what the client claims to have sent; it is a selector, not evidence that the bytes or fields are acceptable. Decide which representations each endpoint promises to accept before registering middleware. Express 5's built-in parsers match configured media types, and the body-parser package reference explicitly excludes multipart uploads.
| Expected request | Typical result after a matching parser | What the handler must still decide |
|---|---|---|
application/json |
Parsed JavaScript value | Object shape, field types, allowed properties |
application/x-www-form-urlencoded |
Field-value object, with string or repeated values | Duplicates, conversion, field rules |
text/plain |
String | Whether free-form text is permitted and how long it may be |
application/octet-stream |
Buffer in Express's raw parser |
Binary format, integrity, and size |
multipart/form-data |
Parts handled by specialized upload middleware | File count, part size, type, and storage policy |

The branches should not converge until each format has been interpreted on its own terms. For example, priority=2 in a URL-encoded form does not become a number just because a TypeScript declaration says priority: number. The db3.ai validation guide notes that its integer rule can accept a numeric string without converting the returned data. Explicitly choose a representation and conversion policy. See the db3.ai validation guide. Multipart boundaries and file streams need a multipart-aware handler rather than express.json() or the standalone body-parser package. Express's body-parser reference lists that limitation.
A webhook presents another distinct case. If its provider requires verification of the original payload bytes, do not parse and reserialize the body before following that provider's signature specification. Express documents a raw parser and a verify callback, but which to use depends on the webhook's protocol. Express 5 parser options describe these facilities. Routes with no relevant request body need no body parser merely because other routes use one.
A TypeScript example with separate JSON and form routes
To make the choice concrete, I would give two preview endpoints different media contracts while sharing the post-parsing check. The routes below accept a title and priority from either a JSON object or a simple URL-encoded form. They return an explicitly selected preview; they do not create a note, authenticate a caller, or implement an owned API. Express supplies the parser; validate() is imported from the documented @db3.ai/app/validation module. Its result's data is the original input, not an automatically sanitized DTO, so the example builds a fresh return object. Express 5 middleware reference, db3.ai validation API, and db3.ai validation walkthrough establish those contracts.
Setup: In a TypeScript ESM application using Express 5, install matching @db3.ai/app and @db3.ai/pure preview tarballs supplied by a maintainer; the db3.ai installation guide says these packages are not yet available through its proposed public npm install and uses Node.js 24 or newer for its walkthroughs. Add express@5, TypeScript, @types/express, @types/node, and a TypeScript runner such as tsx according to your project configuration. Express's TypeScript installation guidance documents the Express types. Save the following as a server entry point after you have completed that setup.
import express from 'express';
import { validate } from '@db3.ai/app/validation';
type Draft = { title: string; priority: number };
function previewDraft(input: unknown, format: 'json' | 'form'): Draft | null {
if (input === null || typeof input !== 'object' || Array.isArray(input)) {
return null;
}
const fields = input as Record<string, unknown>;
if (Object.keys(fields).some(key => !['title', 'priority'].includes(key))) {
return null;
}
if (typeof fields.title !== 'string') return null;
if (format === 'json' && typeof fields.priority !== 'number') return null;
if (format === 'form' &&
(typeof fields.priority !== 'string' || !/^[1-5]$/.test(fields.priority))) {
return null;
}
const candidate = { title: fields.title.trim(), priority: fields.priority };
const checked = validate(candidate, {
title: ['required', 'string', { rule: 'maxLength', value: 120 }],
priority: ['required', 'integer', 'min:1', 'max:5'],
});
if (!checked.valid) return null;
return { title: candidate.title, priority: Number(candidate.priority) };
}
const app = express();
app.post('/api/draft/json', express.json({ limit: '32kb' }), (req, res) => {
if (req.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase() !==
'application/json') {
res.status(415).json({ message: 'Send application/json.' });
return;
}
const draft = previewDraft(req.body as unknown, 'json');
if (!draft) {
res.status(422).json({ message: 'Send a title and numeric priority 1–5.' });
return;
}
res.json({ draft });
});
app.post('/api/draft/form', express.urlencoded({
extended: false,
limit: '8kb',
parameterLimit: 20,
}), (req, res) => {
if (req.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase() !==
'application/x-www-form-urlencoded') {
res.status(415).json({ message: 'Send a URL-encoded form.' });
return;
}
const draft = previewDraft(req.body as unknown, 'form');
if (!draft) {
res.status(422).json({ message: 'Send a title and priority 1–5.' });
return;
}
res.json({ draft });
});
app.listen(3000);

The form branch deliberately rejects repeated priority fields because a repeated field may become an array; it accepts only a single-digit string from 1 to 5 and converts it after validation. JSON requires an actual numeric value. Both branches reject unexpected fields, including a client-supplied ownerId, and return only title and priority. Express documents the extended: false URL-encoded value types and parameterLimit; db3.ai documents that validate() does not remove unknown fields or coerce its returned data. Express body-parser reference and db3.ai validation guide are the relevant contracts.
For a local check, send JSON with Content-Type: application/json and {"title":" Plan ","priority":2} to /api/draft/json; send title=Plan&priority=2 with Content-Type: application/x-www-form-urlencoded to /api/draft/form. Each is intended to yield { "draft": { "title": "Plan", "priority": 2 } }. The code has not been executed as part of writing this article. Add request tests for missing or wrong media types, malformed JSON, repeated fields, oversized payloads, extra fields, and the boundary values. The parser may reject malformed JSON or excessive body size before the route callback runs; configure centralized error handling in a production server rather than assuming the 422 branch catches parser errors. Express's body-parser error catalogue distinguishes parse errors from size failures.
What should happen when parsing fails?
A parser configuration is part of your API contract. Choose byte limits suited to the operation, keep URL-encoded parameter counts bounded, and configure upload-specific limits separately. Do not solve a legitimate file-upload requirement by raising the JSON limit across unrelated routes. The Express parser reference documents limit, parameterLimit, parser errors, and its multipart exclusion.
For diagnosis, follow the request in this order:
req.bodyis missing: Check whether the request actually includes a body, whether itsContent-Typematches the selected parser, and whether middleware runs before the handler. Express leavesreq.bodyundefined without a matching parse. Express 5 request reference.- A field is unexpectedly a string or array: Inspect whether the client sent URL-encoded form data or a repeated key; make the field's conversion and duplicate policy explicit. Express's URL-encoded parser reference.
- Valid-looking JSON fails: Check actual JSON syntax and whether the parser has already consumed the body; invalid JSON is a parsing error, not a db3.ai validation result. Express parser errors.
- A request reaches the wrong branch: Compare the endpoint's accepted media types against the client's
Content-Type; return a controlled unsupported-media response instead of guessing the body shape. Express 5 media matching.
Do not echo a failed request body in an error response or indiscriminately log it. Express notes that parsing errors can carry the received body in the error object. Map expected parser failures to controlled client errors and keep unexpected failures distinct. For a write endpoint, validate first, authenticate and authorize using trusted server context, then persist. Our owned-note JSON API walkthrough shows the separate owner-scoped write boundary; it is not a claim that @db3.ai/app automatically registers these preview routes. Express parser error reference explains what parser failures can expose.
Frequently asked questions
Is the body-parser npm package required in Express 5?
Not for ordinary JSON, URL-encoded, text, or raw parsing when you use Express 5's corresponding built-in middleware. body-parser is also the name of a separate package that exposes these parser families. Inspect your actual HTTP adapter and existing configuration before installing another parser. Express 5 built-in parser reference and standalone body-parser documentation.
Does body parsing validate a request?
No. Parsing decodes a representation; validation checks whether the resulting input satisfies your application's rules. Even a valid draft does not authorize a write. db3.ai's validator returns the original data on success, so select writable fields and derive ownership from authenticated context. db3.ai validation guide.
Why does a file upload need a different parser?
multipart/form-data carries separate parts, often including files. Express's standalone body-parser does not handle multipart bodies; use a multipart-aware upload handler with its own field, file, and storage controls. Express body-parser documentation.
If you are extending a db3.ai application, use the documented input validation boundary to decide what parsed values become application data, then follow the owned-note API guide when you need authenticated persistence. Keep the parser decision in your HTTP adapter and the ownership decision in application code.
Sources
- Node.js v24 HTTP documentation
- Express 5 parser API, request object, and middleware guide
- Express body-parser middleware reference
- Express installation and TypeScript guidance
- db3.ai installation, validation guide, validation API, and owned-note API walkthrough
Recommended Reads
- Bodyparser Explained: How Request-Body Parsing Works in TypeScript APIs: The general concept and a Fastify example.
- Custom Validation Across Forms and APIs: A TypeScript Guide: Add a stricter application-level input contract after parsing.
- How to Create TypeScript APIs With Clear Boundaries, Authentication, and Tests: Continue from input handling to an owned, tested API.