CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-koa-bodyparser

A body parser middleware for Koa.js applications that parses HTTP request bodies in multiple formats including JSON, URL-encoded forms, text, and XML.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

Koa Body Parser

Koa 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.

Package Information

  • Package Name: koa-bodyparser
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install koa-bodyparser

Core Imports

const bodyParser = require('koa-bodyparser');

Note: This package only supports CommonJS. ES module import is not officially supported.

Basic Usage

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);

Architecture

Koa Body Parser is designed as a middleware factory that creates Koa-compatible middleware functions. The architecture includes:

  • Factory Function: The main export creates configured middleware instances
  • Content Type Detection: Uses type-is library for robust content type matching
  • Parsing Engine: Delegates to co-body for actual parsing operations
  • Option Processing: Internal utilities for handling configuration options
  • Error Handling: Configurable error handling with sensible defaults

The middleware follows Koa's async/await pattern and integrates seamlessly with the Koa context object.

Capabilities

Body Parser Factory Function

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']
  }
}));

Dynamic Disabling

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

BodyParserOptions

/**
 * 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;
}

Context Properties

The middleware adds the following properties to the Koa context:

ctx.request.body

/**
 * 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;

ctx.request.rawBody

/**
 * 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;

ctx.disableBodyParser

/**
 * 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;

Default Content Types

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'

Error Handling

The middleware handles the following error scenarios:

  • 413 Payload Too Large: When body size exceeds configured limits (jsonLimit, formLimit, textLimit, xmlLimit)
  • 400 Bad Request: For invalid JSON in strict mode
  • Custom Error Handling: Via the onerror option for customized error responses

Error 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');
    }
  }
}));

Limitations

  • Multipart Forms: Does not support multipart/form-data parsing. Use @koa/multer for file uploads and multipart data.
  • Node.js Version: Requires Node.js >= 8.0.0
  • Koa Version: Designed for Koa v2+. Use koa-bodyparser@2 for Koa v1 compatibility.
  • Memory Usage: Large request bodies are loaded into memory. Configure appropriate size limits to prevent memory exhaustion.

Dependencies

The middleware depends on these core libraries:

  • co-body: Core parsing functionality for different content types
  • copy-to: Object copying utility for option handling
  • type-is: Content type detection and matching
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/koa-bodyparser@4.4.x
Publish Source
CLI
Badge
tessl/npm-koa-bodyparser badge