Request.toNodeListener
Convert Fetch handlers to Node.js
Converts a Fetch API handler into a Node.js HTTP request listener. Useful for running an MPP server on bare node:http without a framework.
Usage
import from 'node:http'
import { } from 'mppx/server'
const = .(() => {
const = new (.).
return new (`Requested ${}`)
}, {
: 1024 * 1024,
})
.().(3000)Request.fromNodeListener
Converts a Node.js IncomingMessage/ServerResponse pair into a Fetch API Request. Useful when you need to manually construct a Request inside existing Node.js middleware.
import type { IncomingMessage, ServerResponse } from 'node:http'
import { Request } from 'mppx/server'
function middleware(req: IncomingMessage, res: ServerResponse) {
const request = Request.fromNodeListener(req, res, { maxBodySize: 1024 * 1024 })
// handle as a Fetch API Request
}The adapter streams Node request bodies with backpressure and rejects bodies larger than maxBodySize. Request.toNodeListener returns 413 Payload Too Large by default. When you call Request.fromNodeListener directly, await Request.waitForBody(request) before committing a successful response so late stream errors and size violations are observed.
Request.waitForBody
Waits for a Node-backed Fetch request body to finish. It resolves immediately for other requests.
const request = Request.fromNodeListener(req, res)
const response = await handler(request)
await Request.waitForBody(request)Parameters
handler
- Type:
(request: Request) => Promise<Response> | Response
A Fetch API handler that receives a Request and returns a Response.
options (optional)
- Type:
{ host?: string; maxBodySize?: number; onError?: (error: unknown) => void | Response | Promise<void | Response>; protocol?: string }
Configures the trusted request origin, body limit, and error response. maxBodySize defaults to 10_485_760 bytes (10 MiB).