Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

koa-better-body

tunnckoCore6.5kMPL-2.03.3.9TypeScript support: definitely-typed

Full-featured [koa][] body parser! Support parsing text, buffer, json, json patch, json api, csp-report, multipart, form and urlencoded bodies. Works for koa@1, koa@2 and will work for koa@3.

api, awesome, better, body, body-parser, buffer, csp, csp-report, error, extendable, feature, features, flexible, form, forms, full, full-feature, handling, json, json-api, koa, koa-better-body, multipart, parse, parser, text, urlencoded

readme

koa-better-body npm version License Libera Manifesto

Full-featured koa body parser! Support parsing text, buffer, json, json patch, json api, csp-report, multipart, form and urlencoded bodies. Works for koa@1, koa@2 and will work for koa@3.

Please consider following this project's author, Charlike Mike Reagent, and :star: the project to show your :heart: and support.

Code style CircleCI linux build CodeCov coverage status Renovate App Status Make A Pull Request Time Since Last Commit

If you have any how-to kind of questions, please read the Contributing Guide and Code of Conduct documents. For bugs reports and feature requests, please create an issue or ping @tunnckoCore at Twitter.

Conventional Commits ![Minimum Required Nodejs][nodejs-img] NPM Downloads Monthly NPM Downloads Total Share Love Tweet Twitter

Project is semantically versioned & automatically released from GitHub Actions with Lerna.

Become a Patron Buy me a Kofi PayPal Donation Bitcoin Coinbase Keybase PGP

Topic Contact
Any legal or licensing questions, like private or commerical use tunnckocore_legal
For any critical problems and security reports tunnckocore_security
Consulting, professional support, personal or team training tunnckocore_consulting
For any questions about Open Source, partnerships and sponsoring tunnckocore_opensource

Features

Table of Contents

(TOC generated by verb using markdown-toc)

Install

This project requires Node.js >=8.11 (see Support & Release Policy). Install it using yarn or npm.
We highly recommend to use Yarn when you think to contribute to this project.

$ yarn add koa-better-body

API

Generated using jest-runner-docs.

koaBetterBody

Robust body parser for koa@1, also works for koa@2 (with deprecations). Will also work for future koa@3 with koa-convert.

Signature

function(options)

Params

  • options {object} - see more on options section
  • returns {GeneratorFunction} - plugin for Koa

Examples

var koa = require('koa');
var body = require('koa-better-body');
var app = koa();

app
  .use(body())
  .use(function* () {
    console.log(this.request.body); // if buffer or text
    console.log(this.request.files); // if multipart or urlencoded
    console.log(this.request.fields); // if json
  })
  .listen(8080, function () {
    console.log('koa server start listening on port 8080');
  });

Working with koa-router

using koa-router

'use strict';

var app = require('koa')();
var body = require('koa-better-body');
var router = require('koa-router')();

router.post('/upload', body(), function* (next) {
  console.log(this.request.files);
  console.log(this.request.fields);

  // there's no `.body` when `multipart`,
  // `urlencoded` or `json` request
  console.log(this.request.body);

  // print it to the API requester
  this.body = JSON.stringify(
    {
      fields: this.request.fields,
      files: this.request.files,
      body: this.request.body || null,
    },
    null,
    2,
  );

  yield next;
});

app.use(router.routes());
app.listen(4292);

var format = require('util').format;
var host = 'http://localhost:4292';
var cmd = 'curl -i %s/upload -F "source=@%s/.editorconfig"';

console.log('Try it out with below CURL for `koa-better-body` repository.');
console.log(format(cmd, host, __dirname));

Options

Sane defaults. :sparkles:

Accepts JSON, JSON API v1, text, buffer, csp-report, multipart and urlencoded/form bodies. If you want to disallow accepting and parsing multipart body you should pass multipart: false. Most of the defaults you can see at utils.defaultOptions and utils.defaultTypes. All options are also been passed to formidable.IncomingForm! Even you can pass IncomingForm instance to be able to handle the different formidable events.

  • fields {Boolean|String}: Default false, which means it will set fields on this.request.fields. If you pass a string, for example 'foo', you will have fields on this.request.foo.
  • files {Boolean|String}: Default false, which means it will set files on this.request.files. If you pass a string, for example 'bar', you will have files on this.request.bar.
  • multipart {Boolean}: Default true. If you pass false it won't accept/parse multipart bodies.
  • textLimit {String}: Default '100kb'. Passed to bytes.parse method.
  • formLimit {String}: Default '100kb'. Passed to bytes.parse method.
  • urlencodedLimit {String}: Default '100kb'. Alias of opts.formLimit.
  • jsonLimit {String}: Default '100kb'. Passed to bytes.parse method.
  • bufferLimit {String}: Default '1mb'. Passed to bytes.parse method.
  • jsonStrict {Boolean}: Default true. When set to true, JSON parser will only accept arrays and objects.
  • detectJSON {Function}: Custom JSON request detect function - detectJSON(ctx).
  • strict {Boolean}: Default true. Pass false if you want to allow parsing GET, DELETE and HEAD requests.
  • onerror {Function}: Custom error handle, if throw an error, you can customize the response - onerror(err, ctx).
  • extendTypes {Object}: Default accepting types can find on utils.defaultTypes function. Allowing you to extend what your app can accept. By default works for JSON, JSON API v1, multipart, text, urlencoded and csp-report.
  • IncomingForm {IncomingForm}: Pass an instance of formidable.IncomingForm to be able to handle formidable events.
  • handler {GeneratorFunction}: Works with options.extendTypes.custom to handle custom types of content-type - handler(ctx, options, next). More info below.
  • querystring {Object}: Querystring module to be used. By default builtin querystring. More info below.
  • qs {Object}: Alias of opts.querystring. All opts are also passed to qs or querystring module.
  • delimiter {String}: Default is &. Delimiter of key/value pairs, passed to querystring lib
  • sep {String}: alias of opts.delimiter
  • buffer {Boolean}: Default false, pass true if you want to get body as buffer.

Note about options.extendTypes

ExandTypes option gives you a flexible way to handle different content-types and modify the defaults which can be found at utils.defaultTypes function. In addition you can pass combination of options.extendTypes.custom and options.handler. When the request has some of the "custom" content type, this middleware will call the handler generator function with ctx, options, next. You can see more at issue #52.

For example manually handle such content types foo/bar-x, text/quix:

const app = require('koa')()
const body = require('koa-better-body')

app.use(body({
  textLimit: '300kb'
  extendTypes: {
    custom: [
      'foo/bar-x',
      'text/quix'
    ]
  },
  handler: function * (ctx, opts) {
    // `ctx` is equal to `this` and `app`
    // `opts` is current options object
    // passed to `koa-better-body`
    ctx.body = yield this.request.text(opts.textLimit)
  }
}))
app.use(function * showBody () {
  // `this.body` is text
  console.log(this.body)
})

Note about advanced querystring parsing

Because this middleware is fully based and integrated with koa-body-parsers, by default it uses Node's built-in module for that thing querystring. So if you have some issues with forms, think to add custom querystring module like qs to options.querystring or app.querystring. Related to this is issue #45.

Example

const app = require('koa')()
const body = require('koa-better-body')

app.use(body({
  multipart: false
  querystring: require('qs')
}))

It's intentional that it's not included in the deps by default. In v2 it was also working by passing it to app.querystring, because koa-body-parsers works that way (index.js#L53).

Note about strict mode

We are trying to follow standards. :cat2:

You can pass strict:false, but see IETF HTTP/1.1 Message Semantics: Section 6.1 to understand why we stay to "strict mode" by default. GET, HEAD, and DELETE requests have no defined semantics for the request body, but this doesn't mean they may not be valid in certain use cases. Last two tests at test/options.js are showing usage on non-strict and strict mode.

back to top

See Also

Some of these projects are used here or were inspiration for this one, others are just related. So, thanks for your existance!

back to top

Contributing

Guides and Community

Please read the Contributing Guide and Code of Conduct documents for advices.

For bug reports and feature requests, please join our community forum and open a thread there with prefixing the title of the thread with the name of the project if there's no separate channel for it.

Consider reading the Support and Release Policy guide if you are interested in what are the supported Node.js versions and how we proceed. In short, we support latest two even-numbered Node.js release lines.

Support the project

Become a Partner or Sponsor? :dollar: Check the OpenSource Commision (tier). :tada: You can get your company logo, link & name on this file. It's also rendered on package's page in npmjs.com and yarnpkg.com sites too! :rocket:

Not financial support? Okey! Pull requests, stars and all kind of contributions are always welcome. :sparkles:

Contributors

This project follows the all-contributors specification. Contributions of any kind are welcome!

Thanks goes to these wonderful people (emoji key), consider showing your support to them:


Charlike Mike Reagent

🚇 💻 📖 🤔 🚧 ⚠️

back to top

License

Copyright (c) 2014-present, Charlike Mike Reagent <opensource@tunnckocore.com> & contributors.
Released under the MPL-2.0 License.

[nodejs-img]: https://badgen.net/badge/node/>=8.11/green?cache=300

changelog

Change Log

All notable changes to this project will be documented in this file. See Conventional Commits for commit guidelines.

3.3.9 (2020-03-28)

Note: Version bump only for package koa-better-body

3.3.8 (2020-03-28)

Note: Version bump only for package koa-better-body

3.3.7 (2020-03-27)

Note: Version bump only for package koa-better-body

3.3.6 (2020-03-27)

Bug Fixes

3.3.5 (2020-02-29)

Bug Fixes

  • switch to latest memoize-fs; update deps; re-run docs; (ab08601)

3.3.4 (2020-02-04)

Bug Fixes

  • docs runner, regen docs, and create-jest-runner updates (d854e3d)
  • dooh, readmes and bugs (871666e)

3.3.3 (2020-02-04)

Bug Fixes

3.3.2 (2020-02-03)

Bug Fixes

  • mass update (docks,configs) + rename workspaces (61ccee3)

3.3.1 (2020-01-24)

Note: Version bump only for package koa-better-body

3.3.0 (2020-01-24)

Bug Fixes

Features

  • format, npm funding field, prettier-plugin-pkgjson (5cd0a38)

3.2.3 (2020-01-19)

Bug Fixes

  • update badges & regenerate readmes (9917d0a)

3.2.2 (2020-01-19)

Bug Fixes

  • badges, regenerate readmes (ccf3b73)

3.2.1 (2020-01-19)

Bug Fixes

  • update param type annotations, regen readmes (783c4b9)
  • docks: supports param's type, run docs -> update readmes (21da65c)

3.2.0 (2019-11-21)

Bug Fixes

  • remove typings field (causing issues like #87) (b154240)

Features

  • eslint lint updates; use typescript parser for js files (36e29cf)

3.1.15 (2019-11-20)

Note: Version bump only for package koa-better-body

3.1.14 (2019-11-20)

Bug Fixes

  • better error handling, regenerate cov data and readmes (f3c98cf)

3.1.13 (2019-10-25)

Bug Fixes

  • cleanup, update deps, update badges (345b7f2)
  • doh, format (af9fac8)
  • handle cases when no tests, so no coverage (e0ce831)
  • per package codecov badge autogen, based on coverage data (4334759)
  • readme badges; some tweaks (95d6666)

3.1.12 (2019-10-22)

Bug Fixes

  • tweaks in koa-better-body, force publish (b73e055)

3.1.11 (2019-10-22)

Bug Fixes

  • update errors in parse-function, run docs+fmt (667c253)

3.1.10 (2019-10-22)

Bug Fixes

  • coverage & coverage thresholds, circleci (be9f64a)

3.1.9 (2019-10-20)

Note: Version bump only for package koa-better-body

3.1.8 (2019-10-20)

Bug Fixes

  • jest-runner-docs: handle errors in postHook (c7c44de)
  • jest-runner-docs: typos (8edc954)
  • koa-better-body: switch to use supertest#end in tests (b27c462)
  • dist files, docs runner updates, docs (c021464), closes #63

3.1.7 (2019-10-18)

Bug Fixes

  • update repository field to support monorepos (7a4f775)

3.1.6 (2019-10-13)

Bug Fixes

  • run prettier on everything (ee3c299)

3.1.5 (2019-10-13)

Note: Version bump only for package koa-better-body

3.1.4 (2019-10-13)

Bug Fixes

  • update readmes, build koa-better-body (698c8d8)

3.1.3 (2019-10-12)

Bug Fixes

  • koa-better-body: make tests passing, update deps (7ef18a3)
  • docs runner readme gen tweaks (87e32b9)
  • remove version from the "promo" part, regen docs (f0dd7ef)

3.1.2 (2019-10-03)

Bug Fixes

  • docs runner updates; use verb; gen readmes (d6a04fe)

3.1.1 (2019-10-03)

Bug Fixes

  • docs runner; gen docs for execa and koa-better-body (93f9638)
  • normalize dashes on param descriptions (5645b72)

3.1.0 (2019-10-02)

Features

  • merge configs repo here, unify pkg json, fmt (0dd53f2)

3.0.11 (2019-10-02)

Bug Fixes

  • koa-better-body: add old changelog entries/versions (35362e5)

3.0.10 (2019-10-02)

Bug Fixes

3.0.9 (2019-10-02)

Note: Version bump only for package koa-better-body

3.0.8 (2019-10-02)

Bug Fixes

  • packages metadata, repo and homepage fields (6a28998)

3.0.7 (2019-10-02)

Note: Version bump only for package koa-better-body

3.0.6 (2019-10-02)

Bug Fixes

  • build to node 8.11, ignore dist again (15481ed)
  • delete dist files (e602f7e)

3.0.4 (2017-07-16)

Bug Fixes

  • lint: update linting, remove lazy-cache (e4ba8da)
  • package: update scripts and travis (63a08ea)
  • prettier: format codebase (e0407cc)
  • style: proper naming (66b91b9)
  • style: update standard and format codebase (e087f02)
  • travis: install more stable npm for better results (2d4b122)

3.0.3 (2017-07-16)

Bug Fixes

  • ampersand: bug when value has ampersand (b4d33f6)
  • doc: update extendTypes link (#82) (280bb1a)
  • koa2: remove ctx.querystring (#84) (e42fdca), closes #77
  • readme: update router example (36e1897)

3.0.2 (2016-10-08)

Bug Fixes

  • utils.js: qs: query string parsing options (a65bd2b), closes #63

3.0.1 (2016-10-08)

Bug Fixes

  • package.json: update npm scripts, remove some devDeps (b5265d8)

3.0.0 (2016-09-12)

For commiting please use npm run commit script.

Starting from this release all the build/pull request/commit chain is changed to follow totally semver, semantic-version and standard-version. Contributing guide is update too, please read it before do anything.

The README.md and CHANGELOG.md files are autogenerated files, so please DO NOT edit them manually - there are tools for that. Readme generation is handled by verb and verb-generate-readme generator, the change log and releasing is handled by standard-version and Git Hooks to follow SemVer more strictly.

The commit message convention is based on Angular's using conventional-changelog which works behind the standard-version. Please follow them while sumbimtting Pull Requests and Bug Reports. If anything is not clear enough in the CONTRIBUTING.md, please open an issue to discuss it and propably change it.

Advanced npm scripts is used to handled any linting and errors. So you won't be able to even push anything if simply running npm test fails. Everything is totally coupled and there's zero chance to do something wrong. From now on, project will follow SemVer more strict than ever.

Most of the files in the repository is scaffolded using the generate tool with generate-charlike-templates generator. So please try to not edit anything.

Features

  • options: add urlencodedLimit alias for formLimit (31ff6c1)
  • parsing: split buffer parsing from text parsing (#52)(81f9a1f)
  • extendTypes: implement extendTypes.custom and opts.handler, (#52)(be10d93)
  • options: add opts.qs and opts.querystring - also possible with app.querystring (cc6ff4d)
  • options: pass options to qs.parse or querystring.parse (e67f42c)
    • so you can now pass custom opts.delimiter (& to be $) for urlencoded bodies

Bug Fixes

  • travis: fails because standard@8 release (6ae0c7f)
  • qs-tests: fix for app.querystring and opts.querystring (c5df3a3)
  • opts-tests: update tests for options (fe1696a)
  • tests: fix possible build fails (522110c)

BREAKING CHANGES

  • ctx.body: no more write to ctx.body (#50) (b927454)
  • utils.handleMuliple: fix incorrect nesting (#55) (56726e9)

Couple of notes are needed here:

  • this.request.files will always be array of files
  • in this.request.fields there have field containing this.request.files array
  • forms with type multipart/form-data now can accept nested fields see #61 if you pass qs module to opts.qs of course, otherwise they will work. In v2 they was just skipped I believe - in this.request i was recieving only the field for type="file"?

2.0.1 (2016-05-05)

  • Release v2.0.1 / npm@v2.0.1
  • fix typo
  • switch to use mukla for testing, instead of assertit - it is drop in replacement
  • add downloads badge
  • bump deps (lazy-cache to v2)

2.0.0 (2016-04-15)

  • Release v2.0.0 / npm@v2.0.0
  • in general, much things was changed and was added new and wanted features - review the v2 PR
  • closed all of the issues marked as todo and v2 (the v2 milestone)
  • in short:
    • cleared all issues marked as todo and v2
    • still using formidable
    • still can pass custom property names for fields and files - e.g. pass options.files: 'foobar'
      • defaults to this.request.fields and this.request.files
      • almost always this.body is equal to this.request.fields (when it make sense)
      • this.request.files not exist always
    • more flexible
      • can pass formidable.IncomingForm instance through options to handle events and etc
      • all options are directly passed to formidable.IncomingForm
    • change options.multipart to be true be default - pass false if you want to disallow it
    • add support for text bodies
    • add options.buffer to get the body as buffer (when text type), defaults to false
    • add options.strict mode to disallow GET, HEAD, DELETE requests, defaults to true
    • add options.jsonStrict JSON parser will only accept arrays and objects, defaults to true
    • add options.detectJSON #16 - same as in [koa-bodyparser]
    • simplified tests
    • simplify a lot of the codebase using koa-body-parsers under the hood

1.0.17 (2015-02-06)

  • Release v1.0.17 / npm@v1.0.17
  • fix license range
  • run update readme
  • update keywords
  • bump deps, actually ranges to ~ only which means only latest patch version

1.0.16 (2015-01-19)

1.0.15 (2015-01-19)

  • Release v1.0.15 / npm@v1.0.15
  • add encode alias for encoding option

1.0.14 (2015-01-18)

  • Release v1.0.14 / npm@v1.0.14
  • istanbul ignore
  • coverage tweaks
  • increase max statements to 20
  • closes #10, update/add tests

1.0.13 (2015-01-17)

  • Release v1.0.13 / npm@v1.0.13
  • update dotfiles and jscs rules
  • revert back filesKey option

1.0.12 (2014-11-27)

  • Release v1.0.12 / npm@v1.0.12
  • bump to jscs >= 1.8.0 and jscs-doc >= 0.2.0
  • update semver range

1.0.11 (2014-11-27)

  • Release v1.0.11 / npm@v1.0.11
  • fix code style collisions

1.0.10 (2014-11-27)

  • Release v1.0.10 / npm@v1.0.10
  • docs, readme, coveralls
  • edit safeContext in .jscsrc

1.0.9 (2014-11-27)

  • Release v1.0.9 / npm@v1.0.9
  • bump jscs-jsdoc to v0.1.0
  • update jscs config .jscsrc

1.0.8 (2014-11-26)

  • Release v1.0.8 / npm@v1.0.8
  • normalize (dot)files
  • update all to apply jshint/jscs code style
    • add .jscsrc and .jshintignore
  • update makefile and scripts in package.json

1.0.7 (2014-10-26)

  • Release v1.0.7 / npm@v1.0.7
  • update names of some tests (rfc7231) "Request Entity Too Large" -> "Payload Too Large"
  • add doc blocks

1.0.6 (2014-10-25)

  • Release v1.0.6 / npm@v1.0.6
  • update automation
  • improve code coverage
  • add Makefile
  • add npm run scripts

1.0.5 (2014-10-25)

1.0.4 (2014-10-21)

1.0.3 (2014-07-03)

  • Release v1.0.3 / npm@v1.0.3
  • Pretty styling
  • auto badges
  • add history
  • add [extend][extend-url], because of options merging bug.
  • add better tests - only 7, for all use cases.
  • need suggestions for error 413 handling, maybe [raw-body][rawbody-url] problem/logic?
  • when upload, always returned type is application/octet-stream, not image/png, image/gif, etc - maybe [formidable][formidable-url] problem/logic?
  • deprecation message also comes from formidable
  • always json and urlencoded bodies will be pushed to request .body.fields object. (fixed in v1.0.4)

1.0.0 (2014-06-08)

0.0.0 (2014-06-08)

  • Initial commits