Skip to content

buffer() returns a string instead of a Buffer when Content-Type has a charset #504

Open

Description

@officialasishkumar

buffer() is typed as Promise<Buffer> and documented as returning the raw body (// <Buffer 7b 22 ...> in the README). In practice it returns a decoded string whenever the request's Content-Type has a charset parameter, because it passes that charset to raw-body as encoding. So the client, not the handler, decides what type buffer() returns.

This was reported in #419, which was closed as stale with an offer to review a PR. It still happens on main (10.0.2).

Reproduction

const { buffer } = require('micro');

module.exports = async (req) => {
  const body = await buffer(req);
  return { isBuffer: Buffer.isBuffer(body) };
};
curl -d 'foo' localhost:3000
# {"isBuffer":true}
curl -d 'foo' -H 'Content-Type: application/json; charset=utf-8' localhost:3000
# {"isBuffer":false}

The decoded string is also what gets cached for the request, so calling json(req) or text(req) first makes a later buffer(req) return a string too.

This breaks code that needs the exact bytes, such as webhook signature verification over the raw body. Many senders (Stripe, for example) include charset=utf-8. It also breaks TypeScript users who rely on the Buffer type, for example by calling body.toString('hex').

Proposal

  • buffer() always resolves with the raw Buffer, and that is what gets cached.
  • text() (and so json()) decodes that buffer with encoding, falling back to the Content-Type charset, the same way it does today. Unsupported charsets and malformed Content-Type headers still return 400 before the body is read.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions