A body parser middleware for Koa.js applications that parses HTTP request bodies in multiple formats including JSON, URL-encoded forms, text, and XML.
npx @tessl/cli install tessl/npm-koa-bodyparser@4.4.0Koa Body Parser is a body parser middleware for Koa.js applications that parses HTTP request bodies in multiple formats including JSON, URL-encoded forms, text, and XML. Built on top of co-body, it offers configurable size limits for different content types, support for custom content-type detection, error handling customization, and the ability to dynamically disable parsing on a per-request basis.
npm install koa-bodyparserconst bodyParser = require('koa-bodyparser');Note: This package only supports CommonJS. ES module import is not officially supported.
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const app = new Koa();
// Use with default options
app.use(bodyParser());
app.use(async ctx => {
// Parsed body will be in ctx.request.body
// Raw body will be in ctx.request.rawBody
console.log('Parsed body:', ctx.request.body);
console.log('Raw body:', ctx.request.rawBody);
ctx.body = ctx.request.body;
});
app.listen(3000);Koa Body Parser is designed as a middleware factory that creates Koa-compatible middleware functions. The architecture includes:
type-is library for robust content type matchingco-body for actual parsing operationsThe middleware follows Koa's async/await pattern and integrates seamlessly with the Koa context object.
The main export is a factory function that creates a Koa middleware function for parsing HTTP request bodies in multiple formats.
/**
* Creates a body parser middleware for Koa applications
* @param {BodyParserOptions} [options] - Configuration options
* @returns {KoaMiddleware} Koa middleware function: (ctx, next) => Promise<void>
*/
function bodyParser(options);
/**
* Default export of the koa-bodyparser module
*/
module.exports = bodyParser;
/**
* Koa middleware function signature
* @typedef {Function} KoaMiddleware
* @param {Context} ctx - Koa context object
* @param {Function} next - Next middleware function
* @returns {Promise<void>}
*/Usage Examples:
// Basic usage with defaults
app.use(bodyParser());
// With custom options
app.use(bodyParser({
jsonLimit: '2mb',
formLimit: '100kb',
enableTypes: ['json', 'form', 'text'],
strict: false,
onerror: (err, ctx) => {
ctx.throw(422, 'Body parsing failed');
}
}));
// With custom JSON detection
app.use(bodyParser({
detectJSON: (ctx) => {
return /\.json$/i.test(ctx.path);
}
}));
// With extended content types
app.use(bodyParser({
extendTypes: {
json: ['application/x-javascript'],
form: ['application/x-my-form'],
text: ['text/html']
}
}));The middleware can be disabled on a per-request basis by setting a context property.
/**
* Disable body parsing for specific requests
* Set ctx.disableBodyParser = true before the bodyParser middleware
*/
ctx.disableBodyParser = true;Usage Example:
app.use(async (ctx, next) => {
// Disable parsing for specific routes
if (ctx.path === '/webhook' || ctx.path.startsWith('/upload/')) {
ctx.disableBodyParser = true;
}
await next();
});
app.use(bodyParser());/**
* Configuration options for the body parser
* @typedef {Object} BodyParserOptions
*/
interface BodyParserOptions {
/**
* Parser will only parse when request type matches these types
* @default ['json', 'form']
*/
enableTypes?: ('json' | 'form' | 'text' | 'xml')[];
/**
* Requested encoding for parsing
* @default 'utf-8'
*/
encoding?: string;
/**
* Limit for JSON body size
* @default '1mb'
*/
jsonLimit?: string;
/**
* Limit for URL-encoded form body size
* @default '56kb'
*/
formLimit?: string;
/**
* Limit for text body size
* @default '1mb'
*/
textLimit?: string;
/**
* Limit for XML body size
* @default '1mb'
*/
xmlLimit?: string;
/**
* When true, JSON parser only accepts arrays and objects, not primitives
* @default true
*/
strict?: boolean;
/**
* Custom function to detect if request should be parsed as JSON
* @default null
*/
detectJSON?: (ctx: Context) => boolean;
/**
* Extend supported content types for each parser
* @default {}
*/
extendTypes?: {
json?: string | string[];
form?: string | string[];
text?: string | string[];
xml?: string | string[];
};
/**
* Custom error handler for parsing errors
* @default undefined
*/
onerror?: (err: Error, ctx: Context) => void;
}
/**
* Koa context object (subset of properties used by body parser)
* @typedef {Object} Context
*/
interface Context {
/** Request object containing body and rawBody after parsing */
request: {
/** Parsed body content - set by the middleware */
body?: any;
/** Raw body string - set by the middleware when parsing occurs */
rawBody?: string;
/** Get request header value */
get(field: string): string | undefined;
/** Check if request matches given content types */
is(types: string | string[]): string | false | null;
};
/** Set to true to disable body parsing for this request */
disableBodyParser?: boolean;
/** Koa's throw method for error handling */
throw(status: number, message?: string): never;
}The middleware adds the following properties to the Koa context:
/**
* Parsed request body content - set by the middleware after parsing
* @type {any}
* @description
* - JSON: Parsed as object/array (or primitive if strict=false)
* - Form: Parsed as object with URL-decoded properties
* - Text/XML: Parsed as string
* - No parseable content: Empty object {}
* - undefined: Before middleware runs or when parsing is disabled
*/
ctx.request.body;/**
* Raw request body as string - set by the middleware when parsing occurs
* @type {string|undefined}
* @description Only set when parsing occurs and wasn't previously set
*/
ctx.request.rawBody;/**
* Flag to skip body parsing for the current request
* @type {boolean}
* @description When set to true before the middleware runs, skips body parsing
*/
ctx.disableBodyParser;The middleware recognizes these content types by default:
JSON Types:
'application/json''application/json-patch+json''application/vnd.api+json''application/csp-report''application/scim+json'Form Types:
'application/x-www-form-urlencoded'Text Types:
'text/plain'XML Types:
'text/xml''application/xml'The middleware handles the following error scenarios:
jsonLimit, formLimit, textLimit, xmlLimit)onerror option for customized error responsesError Handling Example:
app.use(bodyParser({
onerror: (err, ctx) => {
// Log the error
console.error('Body parsing error:', err.message);
// Send custom error response
if (err.status === 413) {
ctx.throw(413, 'Request body too large');
} else if (err.status === 400) {
ctx.throw(400, 'Invalid request body format');
} else {
ctx.throw(422, 'Unable to parse request body');
}
}
}));multipart/form-data parsing. Use @koa/multer for file uploads and multipart data.koa-bodyparser@2 for Koa v1 compatibility.The middleware depends on these core libraries: