{"id":17625,"library":"express-msgpack","title":"Express MessagePack Middleware","description":"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.","status":"active","version":"6.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/textbook/express-msgpack","tags":["javascript","express","middleware","messagepack","msgpack","json","typescript"],"install":[{"cmd":"npm install express-msgpack","lang":"bash","label":"npm"},{"cmd":"yarn add express-msgpack","lang":"bash","label":"yarn"},{"cmd":"pnpm add express-msgpack","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core peer dependency required for Express middleware functionality.","package":"express","optional":false},{"reason":"Default MessagePack encoder/decoder library used internally. It is an optional dependency, meaning custom functions can be provided if it's not installed.","package":"@msgpack/msgpack","optional":true}],"imports":[{"note":"This is the standard ES Module import for `express-msgpack` since v4.0.0. Use this when your project is configured for ES Modules (e.g., `\"type\": \"module\"` in package.json).","wrong":"const msgpack = require('express-msgpack')","symbol":"msgpack","correct":"import msgpack from 'express-msgpack'"},{"note":"This is the recommended CommonJS import for versions >=4.1.0. The direct `.default` access was restored for CJS convenience. The `{ default: ... }` pattern was required specifically for v2.0.0 to v4.0.0.","wrong":"const { default: msgpack } = require('express-msgpack')","symbol":"msgpack","correct":"const msgpack = require('express-msgpack').default"},{"note":"TypeScript type import for configuring the middleware options. Using `import type` ensures it's a compile-time-only import, preventing potential runtime issues or unnecessary bundle size increases.","wrong":"import { ExpressMsgpackOptions } from 'express-msgpack'","symbol":"ExpressMsgpackOptions","correct":"import type { ExpressMsgpackOptions } from 'express-msgpack'"}],"quickstart":{"code":"import express from 'express';\nimport msgpack from 'express-msgpack';\nimport { pack, unpack } from 'msgpack'; // Example: Using an alternative MessagePack library\n\nconst app = express();\nconst port = 3000;\n\n// Basic usage: Initialize the middleware. It will use @msgpack/msgpack by default.\napp.use(msgpack());\n\n// Example with custom encoder/decoder functions and additional options:\n/*\napp.use(msgpack({\n  decoder: unpack, // Custom function to decode MessagePack bytes to JS object\n  encoder: (obj) => Buffer.from(pack(obj)), // Custom function to encode JS object to MessagePack Buffer\n  limit: '1mb', // Set the maximum request body size\n  mimeType: 'application/x-msgpack', // Custom MIME type if needed\n  allowUnacceptableResponse: true // Send MessagePack even if client's Accept header doesn't explicitly include it\n}));\n*/\n\napp.get('/', (req, res) => {\n  // If the client's Accept header includes 'application/msgpack', the response will be MessagePack encoded.\n  res.json({ message: 'Hello from Express, potentially MessagePack encoded!' });\n});\n\napp.post('/data', express.json(), (req, res) => {\n  // If client sends Content-Type: application/msgpack, req.body will be automatically decoded.\n  // This endpoint also accepts standard JSON for demonstration.\n  console.log('Received MessagePack or JSON data:', req.body);\n  res.status(200).json({ received: req.body, status: 'processed' });\n});\n\napp.listen(port, () => {\n  console.log(`Server listening on http://localhost:${port}`);\n});","lang":"typescript","description":"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."},"warnings":[{"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).","message":"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.","severity":"breaking","affected_versions":">=6.0.0"},{"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.","message":"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.","severity":"breaking","affected_versions":">=4.0.0"},{"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.","message":"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`.","severity":"breaking","affected_versions":">=2.0.0 <4.1.0"},{"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 }))`.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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 }))`.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"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.","cause":"This typically occurs in TypeScript or CommonJS projects when the `express-msgpack` default export is not accessed correctly, especially after version changes.","error":"TypeError: express_msgpack_1.default is not a function"},{"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).","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.","error":"SyntaxError: Cannot use import statement outside a module"},{"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.","cause":"The incoming MessagePack or JSON payload size exceeds the configured `limit` option for the `express-msgpack` middleware.","error":"Error: The body size limit has been reached"},{"fix":"If you are using a custom `encoder` function, verify that it correctly serializes your JavaScript object into a valid MessagePack `Buffer` or `Uint8Array`.","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.","error":"RangeError: Out of range index"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}