Express MessagePack Middleware

raw JSON →
6.0.0 verified Thu Apr 23 auth: no javascript

express-msgpack is an Express middleware that provides transparent support for MessagePack (msgpack) content types, enabling developers to handle `application/msgpack` requests and responses using standard Express `req.body` and `res.json` patterns. It automatically decodes incoming MessagePack payloads into JavaScript objects and encodes outgoing JavaScript objects into MessagePack format when clients request it via the `Accept` header. The current stable version is 6.0.0, which mandates Node.js 20.12.0 or higher. The package is actively maintained with releases frequently aligned with Node.js version updates and new features such as `allowUnacceptableResponse` and `limit` options. A key differentiator is its seamless integration with existing Express API patterns, which reduces boilerplate, and the flexibility to utilize custom MessagePack encoder/decoder libraries.

error TypeError: express_msgpack_1.default is not a function
cause This typically occurs in TypeScript or CommonJS projects when the `express-msgpack` default export is not accessed correctly, especially after version changes.
fix
For CJS, try const msgpack = require('express-msgpack').default; (for v4.1.0+). For older CJS versions (v2.x-v4.0.0), use const { default: msgpack } = require('express-msgpack');. In TypeScript, ensure your tsconfig.json moduleResolution and allowSyntheticDefaultImports are configured appropriately, or stick to explicit require().default for CJS.
error SyntaxError: Cannot use import statement outside a module
cause Attempting to use ES module `import` syntax in a CommonJS project, particularly relevant for `express-msgpack` v4.0.0 which initially switched to ESM as its primary module format.
fix
Configure your project as an ES module by adding "type": "module" to your package.json file, or switch to the correct CommonJS require syntax: const msgpack = require('express-msgpack').default; (since v4.1.0).
error Error: The body size limit has been reached
cause The incoming MessagePack or JSON payload size exceeds the configured `limit` option for the `express-msgpack` middleware.
fix
Increase the limit option when initializing the middleware, e.g., app.use(msgpack({ limit: '5mb' })). Ensure the limit string format is supported by the bytes package.
error RangeError: Out of range index
cause This can occur if a custom MessagePack `encoder` function does not return a `Buffer` or `Uint8Array`, or if the returned data is not valid MessagePack, leading to parsing failures down the line.
fix
If you are using a custom encoder function, verify that it correctly serializes your JavaScript object into a valid MessagePack Buffer or Uint8Array.
breaking Version 6.0.0 dropped support for Node.js v18. The minimum required Node.js version is now 20.12.0. Ensure your runtime environment meets this requirement before upgrading.
fix Upgrade your Node.js runtime to version 20.12.0 or higher. If unable to upgrade Node.js, you must remain on an older `express-msgpack` version compatible with your current Node.js runtime (e.g., v5.x for Node.js v18).
breaking Version 4.0.0 introduced a switch to ES Modules internally and dropped Node.js v12 support, followed by v5.0.0 dropping Node.js v14 support. This means `import` syntax became primary. While CommonJS support was later restored in v4.1.0, the underlying package structure remained ESM.
fix For ES Module projects, use `import msgpack from 'express-msgpack';`. For CommonJS projects, use `const msgpack = require('express-msgpack').default;` (since v4.1.0). Always verify your Node.js version meets the requirements of the specific major version of `express-msgpack` you are using.
breaking Version 2.0.0 changed the CommonJS import pattern. Previously, a direct `require("express-msgpack")` was used. This shifted to `const { default: msgpack } = require("express-msgpack")` until v4.1.0, which then reverted to `require().default`.
fix Update your CommonJS import statements according to your `express-msgpack` version: use `const { default: msgpack } = require("express-msgpack");` for versions 2.x up to 4.0.0, or `const msgpack = require("express-msgpack").default;` for versions 4.1.0 and later.
gotcha The `@msgpack/msgpack` library is an optional dependency. If you install `express-msgpack` using `--no-optional` with npm or yarn, or if `@msgpack/msgpack` fails to install, you *must* provide custom `decoder` and `encoder` functions in the middleware options.
fix Ensure `@msgpack/msgpack` is successfully installed (it's installed by default). If you intend to use a different MessagePack library, explicitly pass its `decoder` and `encoder` functions: `app.use(msgpack({ decoder: yourDecoder, encoder: yourEncoder }))`.
gotcha By default, `express-msgpack` responds with a `406 Not Acceptable` status if the client explicitly requests `application/msgpack` but does not include it in its `Accept` header. This can lead to unexpected errors for clients that assume MessagePack responses without proper content negotiation.
fix To allow `express-msgpack` to send MessagePack responses even if `application/msgpack` is not explicitly in the client's `Accept` header, set the `allowUnacceptableResponse` option to `true`: `app.use(msgpack({ allowUnacceptableResponse: true }))`.
npm install express-msgpack
yarn add express-msgpack
pnpm add express-msgpack

Demonstrates setting up a basic Express server with `express-msgpack` middleware. It shows how to initialize the middleware for transparent MessagePack handling and includes commented-out examples for configuring custom encoder/decoder functions and other options like `limit` and `allowUnacceptableResponse`. It handles both GET and POST requests, highlighting how `res.json` and `req.body` adapt to MessagePack content negotiation.

import express from 'express';
import msgpack from 'express-msgpack';
import { pack, unpack } from 'msgpack'; // Example: Using an alternative MessagePack library

const app = express();
const port = 3000;

// Basic usage: Initialize the middleware. It will use @msgpack/msgpack by default.
app.use(msgpack());

// Example with custom encoder/decoder functions and additional options:
/*
app.use(msgpack({
  decoder: unpack, // Custom function to decode MessagePack bytes to JS object
  encoder: (obj) => Buffer.from(pack(obj)), // Custom function to encode JS object to MessagePack Buffer
  limit: '1mb', // Set the maximum request body size
  mimeType: 'application/x-msgpack', // Custom MIME type if needed
  allowUnacceptableResponse: true // Send MessagePack even if client's Accept header doesn't explicitly include it
}));
*/

app.get('/', (req, res) => {
  // If the client's Accept header includes 'application/msgpack', the response will be MessagePack encoded.
  res.json({ message: 'Hello from Express, potentially MessagePack encoded!' });
});

app.post('/data', express.json(), (req, res) => {
  // If client sends Content-Type: application/msgpack, req.body will be automatically decoded.
  // This endpoint also accepts standard JSON for demonstration.
  console.log('Received MessagePack or JSON data:', req.body);
  res.status(200).json({ received: req.body, status: 'processed' });
});

app.listen(port, () => {
  console.log(`Server listening on http://localhost:${port}`);
});