Middy JSONAPI Middleware
raw JSON → 2.0.2 verified Sat Apr 25 auth: no javascript
middy-jsonapi (v2.0.2) is a middleware for the Middy Node.js AWS Lambda framework that formats Lambda responses to conform to the JSON API spec (jsonapi.org). It parses query parameters like include, fields, sort, and page, supports page-based and offset-based pagination with auto-generated links, and formats errors into standard JSON API error objects. Unlike manual formatting, it integrates seamlessly with Middy's middleware chain (e.g., validator, httpContentNegotiation) and works with strict Accept headers (application/vnd.api+json). Requires middy as a peer dependency. Active development, release cadence irregular.
Common errors
error Cannot find module 'middy-jsonapi' ↓
cause Package not installed or incorrect import path (CommonJS require used with ESM package).
fix
Run npm install middy-jsonapi and ensure you use import (ESM) not require().
error TypeError: jsonapi is not a function ↓
cause Attempted to import named export { jsonapi } from 'middy-jsonapi' but only default export exists.
fix
Use import jsonapi from 'middy-jsonapi' without curly braces.
Warnings
breaking In v2.0.0, the package switched to ESM-only. CommonJS require() will fail. ↓
fix Use import jsonapi from 'middy-jsonapi' or use dynamic import().
gotcha The Accept header must be exactly 'application/vnd.api+json' or the middleware may not process response correctly. ↓
fix Ensure httpContentNegotiation or a custom middleware sets the Accept header to the required media type.
deprecated The 'cache' middleware from middy is optionally used but may be removed in future versions. ↓
fix Consider using an alternative caching mechanism or check compatibility.
Install
npm install middy-jsonapi yarn add middy-jsonapi pnpm add middy-jsonapi Imports
- jsonapi wrong
const jsonapi = require('middy-jsonapi')correctimport jsonapi from 'middy-jsonapi' - middleware wrong
import { jsonapi } from 'middy-jsonapi'correctimport jsonapi from 'middy-jsonapi' - TypeScript wrong
import * as jsonapi from 'middy-jsonapi'correctimport jsonapi from 'middy-jsonapi'
Quickstart
import middy from 'middy';
import jsonapi from 'middy-jsonapi';
const handler = middy(async (event, context) => {
return {
statusCode: 200,
body: JSON.stringify({
data: { type: 'articles', id: '1', attributes: { title: 'Hello' } }
})
};
});
handler.use(jsonapi({
response: {
jsonapi: { version: '1.0' },
meta: { version: '1.0.0', copyright: '2023' }
}
}));
// Example invocation (AWS Lambda event)
const event = {
httpMethod: 'GET',
headers: { Accept: 'application/vnd.api+json' },
queryStringParameters: { include: 'author', page: '1' }
};
handler(event, {}).then(res => console.log(res));