@molecule/api-middleware-body-parser

Middleware · body-parser · API (Node) · v1.2.0 · Apache-2.0

Body parser middleware interface (JSON and multipart)

npm install @molecule/api-middleware-body-parser

npm · Source on GitHub

How it works

@molecule/api-middleware-body-parser is body-parser middleware for the API, mounted once at startup.

import { createJsonParser } from '@molecule/api-middleware-body-parser'
// Webhook route FIRST, with a raw parser, so signature verification sees the exact bytes.
app.post(
  '/api/users/payment-notification/stripe',
  express.raw({ type: 'application/json' }),
  stripeWebhookHandler,
)
// Then the global JSON parser (bounded) for everything else.
app.use(createJsonParser({ limit: '1mb' }))

Providers (1): @molecule/api-middleware-body-parser-express

Works with: @molecule/api-bond

Reference

Body parser middleware for molecule.dev.

Core interface — the actual implementation is provided via bonds. Install a body parser bond (e.g., @molecule/api-middleware-body-parser-express) to provide JSON and URL-encoded parsing app-wide, and multipart file uploads per route.

A multipart/form-data body is read only by the route's upload parser (createUploadParser; apps call it through receiveUploads() from @molecule/api-uploads). The app-wide parser leaves it unread, so an upload route works wherever it is mounted.

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

import { createJsonParser } from '@molecule/api-middleware-body-parser'
// Webhook route FIRST, with a raw parser, so signature verification sees the exact bytes.
app.post(
  '/api/users/payment-notification/stripe',
  express.raw({ type: 'application/json' }),
  stripeWebhookHandler,
)
// Then the global JSON parser (bounded) for everything else.
app.use(createJsonParser({ limit: '1mb' }))

Type

middleware

Installation

npm install @molecule/api-middleware-body-parser @molecule/api-bond

API

Interfaces

JsonParserOptions

Options for JSON body parsing (limit, strict mode, content type).

interface JsonParserOptions {
  limit?: string | number
  strict?: boolean
  type?: string | string[]
}

UploadPartInfo

What the parser tells storage about one file part, as the client declared it.

interface UploadPartInfo {
  /** The client's filename, `undefined` when it sent none. Never use it as a storage key. */
  filename: string | undefined
  /** The part's transfer encoding, e.g. `7bit`. */
  encoding: string
  /** The part's declared MIME type, e.g. `image/png`. The client chooses it. */
  mimeType: string
}

StoredUpload

A file storage is receiving or has received.

interface StoredUpload {
  /** The storage id. */
  id: string
  /** Settles when the file is fully written; rejects when writing fails or is aborted. */
  uploadPromise?: Promise<void>
}

StorageRefusal

An error a storage passes to onError to refuse a file rather than to report that storing it failed (a type it will not keep): the parser answers status (4xx) with the message of errorKey as JSON, as it answers its own refusals. UploadRefusedError from @molecule/api-uploads has this shape.

interface StorageRefusal extends Error {
  /** The HTTP status to answer, 400-499. */
  status: number
  /** The translation key of the message. */
  errorKey: string
  /** The values the message interpolates. */
  values?: Record<string, string | number>
}

UploadStorage

Where an upload parser stores accepted file parts. The bonded uploads provider of @molecule/api-uploads has this shape.

interface UploadStorage<F extends StoredUpload = StoredUpload> {
  /**
   * Start storing one file part.
   *
   * @param fieldname - The form field the part was sent in.
   * @param stream - The part's bytes.
   * @param info - What the client declared about the part.
   * @param onError - Called when storing fails, or with a `StorageRefusal` to refuse the
   *   file: the client gets that status, not a server error.
   * @returns The file being stored.
   */
  upload(
    fieldname: string,
    stream: NodeJS.ReadableStream,
    info: UploadPartInfo,
    onError: (error: Error) => void,
  ): F
  /**
   * Stop storing a file whose `uploadPromise` is still pending and remove what was written.
   *
   * @param file - The file being stored.
   */
  abortUpload(file: F): void | Promise<void>
  /**
   * Remove a stored file.
   *
   * @param id - Its storage id.
   */
  deleteFile(id: string): Promise<void>
}

UploadParserOptions

What one route accepts. Anything outside it is refused before the handler runs. A bond applies the DEFAULT_* limits above to the ones a route leaves out.

@molecule/api-uploads declares the same fields (less storage) as ReceiveUploadsOptions, so a route reads them in one place: change both together.

interface UploadParserOptions<F extends StoredUpload = StoredUpload> {
  /** The form field the files are sent in. A file in any other field is refused with 400. */
  field: string
  /**
   * The largest file accepted, in bytes (default `DEFAULT_MAX_FILE_BYTES`, 10 MiB). A larger
   * one is refused with 413.
   */
  maxFileBytes?: number
  /** The most files accepted in `field` (default 1). More are refused with 413. */
  maxFiles?: number
  /**
   * The MIME types accepted, as the client declares them (`'image/png'`, or `'image/*'` for a
   * whole family). Another type is refused with 415. Omit it to accept any type.
   */
  types?: readonly string[]
  /** When false, a request with no file passes with none; by default it is refused with 400. */
  required?: boolean
  /** The most text fields accepted (default `DEFAULT_MAX_FIELDS`); they become `req.body`, as strings. */
  maxFields?: number
  /**
   * The largest text field, in bytes (default `DEFAULT_MAX_FIELD_BYTES`, 64 KiB). A larger one
   * is refused with 413.
   */
  maxFieldBytes?: number
  /** The storage for this request's files, read when a request arrives. */
  storage: () => UploadStorage<F>
}

Types

Middleware

Generic middleware type — framework-agnostic.

type Middleware = (req: unknown, res: unknown, next: (err?: unknown) => void) => void
  • req — The request object.
  • res — The response object.
  • next — The next middleware function.

JsonParserFactory

Factory function type for creating JSON parsers with options.

type JsonParserFactory = (options?: JsonParserOptions) => Middleware

UploadParserFactory

Creates a route's upload parser. It answers 415 for a body that is not multipart, 400 for a malformed one, and stores accepted files only after the checks above pass. When any check fails, storage fails, or the client disconnects, it removes every file it stored for the request. The handler runs only when every file is fully stored.

The parser goes on owning them after the handler starts. When the route answers with a status of 400 or more, it removes the files the request still lists through getParsedUploads; a 2xx or 3xx answer keeps them, and so does a client that goes away before the answer. Whatever removes a stored file itself takes it off that list with setParsedUploads, so nothing removes a file twice.

type UploadParserFactory = <F extends StoredUpload>(options: UploadParserOptions<F>) => Middleware

Functions

setBodyParser(parser)

Bonds a body parser middleware implementation for use by getBodyParser() and bodyParser.

function setBodyParser(parser: Middleware): void
  • parser — The middleware function that parses request bodies.

getBodyParser()

Gets the bonded body parser middleware.

function getBodyParser(): Middleware

Returns: The bonded body parser middleware function.

hasBodyParser()

Checks if a body parser middleware has been bonded.

function hasBodyParser(): boolean

Returns: true if a body parser is available.

setJsonParserFactory(factory)

Bonds a JSON parser factory for creating parsers with custom options (e.g., size limits).

function setJsonParserFactory(factory: JsonParserFactory): void
  • factory — A function that creates JSON parser middleware from options.

getJsonParserFactory()

Gets the bonded JSON parser factory.

function getJsonParserFactory(): JsonParserFactory | null

Returns: The factory function, or null if none has been bonded.

bodyParser(req, res, next)

Default body parser middleware that delegates to the bonded implementation.

function bodyParser(req: unknown, res: unknown, next: (err?: unknown) => void): void
  • req — The incoming request object.
  • res — The response object.
  • next — The next middleware function.

Returns: The result of the bonded body parser invocation.

createJsonParser(options)

Creates a JSON body parser with custom options via the bonded factory.

function createJsonParser(options?: JsonParserOptions): Middleware
  • options — JSON parsing options (limit, strict mode, content type).

Returns: A middleware function that parses JSON request bodies.

setUploadParserFactory(factory)

Bonds the upload parser factory createUploadParser uses.

function setUploadParserFactory(factory: UploadParserFactory): void
  • factory — A body parser bond's upload parser factory.

getUploadParserFactory()

Gets the bonded upload parser factory.

function getUploadParserFactory(): UploadParserFactory | null

Returns: The factory, or null if none has been bonded.

createUploadParser(options)

Creates a route's upload parser through the bonded factory. The factory is looked up on the first request, so a router can be built before the bonds are wired.

function createUploadParser<F extends StoredUpload>(options: UploadParserOptions<F>): Middleware
  • options — What the route accepts and where its files are stored.

Returns: Middleware to put on the route, after its authentication check.

setParsedUploads(req, field, files)

Records the files an upload parser stored for a request. Called by body parser bonds.

function setParsedUploads<F extends StoredUpload>(req: unknown, field: string, files: F[]): void
  • req — The request.
  • field — The form field the files came in.
  • files — The stored files, in arrival order.

getParsedUploads(req, field)

The files the route's upload parser stored for a request and that are still in storage: the list the parser removes when the route fails after the upload. Whatever removes one of them itself takes it off the list, with setParsedUploads.

function getParsedUploads<F extends StoredUpload>(req: unknown, field?: string): F[]
  • req — The request.
  • field — The form field, or every field when omitted.

Returns: The stored files, in arrival order; empty when there are none.

Constants

DEFAULT_MAX_FILE_BYTES

The largest file a route accepts when it names no maxFileBytes: 10 MiB.

const DEFAULT_MAX_FILE_BYTES: number

DEFAULT_MAX_FIELDS

The most text fields a route accepts when it names no maxFields.

const DEFAULT_MAX_FIELDS: 20

DEFAULT_MAX_FIELD_BYTES

The largest text field a route accepts when it names no maxFieldBytes: 64 KiB.

const DEFAULT_MAX_FIELD_BYTES: number

Available Providers

ProviderPackage
Body Parser (Express)@molecule/api-middleware-body-parser-express

Injection Notes

Requirements

Peer dependencies:

  • @molecule/api-bond ^1.0.1

Runtime Dependencies

  • @molecule/api-bond

  • Always set a limit (JsonParserOptions``.limit, e.g. '1mb'). An unbounded body lets a client exhaust memory (DoS) — pick a cap that fits your largest legit payload.

  • Provider webhooks need the RAW body — mount their route BEFORE the JSON parser. A JSON parser consumes + rewrites the body, which breaks signature verification (Stripe's constructEvent and friends hash the exact bytes). Give the webhook route express.raw(...) (or capture req.rawBody) and register it before the global JSON body parser. See @molecule/api-payments-stripe.