or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md
tile.json

index.mddocs/

0

# Koa Body Parser

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: koa-bodyparser

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install koa-bodyparser`

10

11

## Core Imports

12

13

```javascript

14

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

15

```

16

17

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

18

19

## Basic Usage

20

21

```javascript

22

const Koa = require('koa');

23

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

24

25

const app = new Koa();

26

27

// Use with default options

28

app.use(bodyParser());

29

30

app.use(async ctx => {

31

// Parsed body will be in ctx.request.body

32

// Raw body will be in ctx.request.rawBody

33

console.log('Parsed body:', ctx.request.body);

34

console.log('Raw body:', ctx.request.rawBody);

35

ctx.body = ctx.request.body;

36

});

37

38

app.listen(3000);

39

```

40

41

## Architecture

42

43

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

44

45

- **Factory Function**: The main export creates configured middleware instances

46

- **Content Type Detection**: Uses `type-is` library for robust content type matching

47

- **Parsing Engine**: Delegates to `co-body` for actual parsing operations

48

- **Option Processing**: Internal utilities for handling configuration options

49

- **Error Handling**: Configurable error handling with sensible defaults

50

51

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

52

53

## Capabilities

54

55

### Body Parser Factory Function

56

57

The main export is a factory function that creates a Koa middleware function for parsing HTTP request bodies in multiple formats.

58

59

```javascript { .api }

60

/**

61

* Creates a body parser middleware for Koa applications

62

* @param {BodyParserOptions} [options] - Configuration options

63

* @returns {KoaMiddleware} Koa middleware function: (ctx, next) => Promise<void>

64

*/

65

function bodyParser(options);

66

67

/**

68

* Default export of the koa-bodyparser module

69

*/

70

module.exports = bodyParser;

71

72

/**

73

* Koa middleware function signature

74

* @typedef {Function} KoaMiddleware

75

* @param {Context} ctx - Koa context object

76

* @param {Function} next - Next middleware function

77

* @returns {Promise<void>}

78

*/

79

```

80

81

**Usage Examples:**

82

83

```javascript

84

// Basic usage with defaults

85

app.use(bodyParser());

86

87

// With custom options

88

app.use(bodyParser({

89

jsonLimit: '2mb',

90

formLimit: '100kb',

91

enableTypes: ['json', 'form', 'text'],

92

strict: false,

93

onerror: (err, ctx) => {

94

ctx.throw(422, 'Body parsing failed');

95

}

96

}));

97

98

// With custom JSON detection

99

app.use(bodyParser({

100

detectJSON: (ctx) => {

101

return /\.json$/i.test(ctx.path);

102

}

103

}));

104

105

// With extended content types

106

app.use(bodyParser({

107

extendTypes: {

108

json: ['application/x-javascript'],

109

form: ['application/x-my-form'],

110

text: ['text/html']

111

}

112

}));

113

```

114

115

### Dynamic Disabling

116

117

The middleware can be disabled on a per-request basis by setting a context property.

118

119

```javascript { .api }

120

/**

121

* Disable body parsing for specific requests

122

* Set ctx.disableBodyParser = true before the bodyParser middleware

123

*/

124

ctx.disableBodyParser = true;

125

```

126

127

**Usage Example:**

128

129

```javascript

130

app.use(async (ctx, next) => {

131

// Disable parsing for specific routes

132

if (ctx.path === '/webhook' || ctx.path.startsWith('/upload/')) {

133

ctx.disableBodyParser = true;

134

}

135

await next();

136

});

137

138

app.use(bodyParser());

139

```

140

141

## Configuration Options

142

143

### BodyParserOptions

144

145

```javascript { .api }

146

/**

147

* Configuration options for the body parser

148

* @typedef {Object} BodyParserOptions

149

*/

150

interface BodyParserOptions {

151

/**

152

* Parser will only parse when request type matches these types

153

* @default ['json', 'form']

154

*/

155

enableTypes?: ('json' | 'form' | 'text' | 'xml')[];

156

157

/**

158

* Requested encoding for parsing

159

* @default 'utf-8'

160

*/

161

encoding?: string;

162

163

/**

164

* Limit for JSON body size

165

* @default '1mb'

166

*/

167

jsonLimit?: string;

168

169

/**

170

* Limit for URL-encoded form body size

171

* @default '56kb'

172

*/

173

formLimit?: string;

174

175

/**

176

* Limit for text body size

177

* @default '1mb'

178

*/

179

textLimit?: string;

180

181

/**

182

* Limit for XML body size

183

* @default '1mb'

184

*/

185

xmlLimit?: string;

186

187

/**

188

* When true, JSON parser only accepts arrays and objects, not primitives

189

* @default true

190

*/

191

strict?: boolean;

192

193

/**

194

* Custom function to detect if request should be parsed as JSON

195

* @default null

196

*/

197

detectJSON?: (ctx: Context) => boolean;

198

199

/**

200

* Extend supported content types for each parser

201

* @default {}

202

*/

203

extendTypes?: {

204

json?: string | string[];

205

form?: string | string[];

206

text?: string | string[];

207

xml?: string | string[];

208

};

209

210

/**

211

* Custom error handler for parsing errors

212

* @default undefined

213

*/

214

onerror?: (err: Error, ctx: Context) => void;

215

}

216

217

/**

218

* Koa context object (subset of properties used by body parser)

219

* @typedef {Object} Context

220

*/

221

interface Context {

222

/** Request object containing body and rawBody after parsing */

223

request: {

224

/** Parsed body content - set by the middleware */

225

body?: any;

226

/** Raw body string - set by the middleware when parsing occurs */

227

rawBody?: string;

228

/** Get request header value */

229

get(field: string): string | undefined;

230

/** Check if request matches given content types */

231

is(types: string | string[]): string | false | null;

232

};

233

/** Set to true to disable body parsing for this request */

234

disableBodyParser?: boolean;

235

/** Koa's throw method for error handling */

236

throw(status: number, message?: string): never;

237

}

238

```

239

240

## Context Properties

241

242

The middleware adds the following properties to the Koa context:

243

244

### ctx.request.body

245

246

```javascript { .api }

247

/**

248

* Parsed request body content - set by the middleware after parsing

249

* @type {any}

250

* @description

251

* - JSON: Parsed as object/array (or primitive if strict=false)

252

* - Form: Parsed as object with URL-decoded properties

253

* - Text/XML: Parsed as string

254

* - No parseable content: Empty object {}

255

* - undefined: Before middleware runs or when parsing is disabled

256

*/

257

ctx.request.body;

258

```

259

260

### ctx.request.rawBody

261

262

```javascript { .api }

263

/**

264

* Raw request body as string - set by the middleware when parsing occurs

265

* @type {string|undefined}

266

* @description Only set when parsing occurs and wasn't previously set

267

*/

268

ctx.request.rawBody;

269

```

270

271

### ctx.disableBodyParser

272

273

```javascript { .api }

274

/**

275

* Flag to skip body parsing for the current request

276

* @type {boolean}

277

* @description When set to true before the middleware runs, skips body parsing

278

*/

279

ctx.disableBodyParser;

280

```

281

282

## Default Content Types

283

284

The middleware recognizes these content types by default:

285

286

**JSON Types:**

287

- `'application/json'`

288

- `'application/json-patch+json'`

289

- `'application/vnd.api+json'`

290

- `'application/csp-report'`

291

- `'application/scim+json'`

292

293

**Form Types:**

294

- `'application/x-www-form-urlencoded'`

295

296

**Text Types:**

297

- `'text/plain'`

298

299

**XML Types:**

300

- `'text/xml'`

301

- `'application/xml'`

302

303

## Error Handling

304

305

The middleware handles the following error scenarios:

306

307

- **413 Payload Too Large**: When body size exceeds configured limits (`jsonLimit`, `formLimit`, `textLimit`, `xmlLimit`)

308

- **400 Bad Request**: For invalid JSON in strict mode

309

- **Custom Error Handling**: Via the `onerror` option for customized error responses

310

311

**Error Handling Example:**

312

313

```javascript

314

app.use(bodyParser({

315

onerror: (err, ctx) => {

316

// Log the error

317

console.error('Body parsing error:', err.message);

318

319

// Send custom error response

320

if (err.status === 413) {

321

ctx.throw(413, 'Request body too large');

322

} else if (err.status === 400) {

323

ctx.throw(400, 'Invalid request body format');

324

} else {

325

ctx.throw(422, 'Unable to parse request body');

326

}

327

}

328

}));

329

```

330

331

## Limitations

332

333

- **Multipart Forms**: Does not support `multipart/form-data` parsing. Use `@koa/multer` for file uploads and multipart data.

334

- **Node.js Version**: Requires Node.js >= 8.0.0

335

- **Koa Version**: Designed for Koa v2+. Use `koa-bodyparser@2` for Koa v1 compatibility.

336

- **Memory Usage**: Large request bodies are loaded into memory. Configure appropriate size limits to prevent memory exhaustion.

337

338

## Dependencies

339

340

The middleware depends on these core libraries:

341

342

- **co-body**: Core parsing functionality for different content types

343

- **copy-to**: Object copying utility for option handling

344

- **type-is**: Content type detection and matching