Express MessagePack Middleware
raw JSON →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.
Common errors
error TypeError: express_msgpack_1.default is not a function ↓
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 ↓
"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 ↓
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 ↓
encoder function, verify that it correctly serializes your JavaScript object into a valid MessagePack Buffer or Uint8Array. Warnings
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. ↓
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. ↓
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`. ↓
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. ↓
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. ↓
Install
npm install express-msgpack yarn add express-msgpack pnpm add express-msgpack Imports
- msgpack wrong
const msgpack = require('express-msgpack')correctimport msgpack from 'express-msgpack' - msgpack wrong
const { default: msgpack } = require('express-msgpack')correctconst msgpack = require('express-msgpack').default - ExpressMsgpackOptions wrong
import { ExpressMsgpackOptions } from 'express-msgpack'correctimport type { ExpressMsgpackOptions } from 'express-msgpack'
Quickstart
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}`);
});