next-api-compose v2.1.1
Next.js API Compose ยท

Introduction
This library provides simple yet complete higher order function
with responsibility of composing multiple middleware functions into one Next.js API route handler.
The library does not contain routing utilities. I believe mechanism built in
Next.js itself or next-connect library are sufficient solutions.
Features
- ๐ Simple and powerful API
- ๐ฅท TypeScript support
- ๐งฌ Maintaining order of middleware chain
- ๐ง Compatible with Express/Connect middleware
- ๐ข Error handling
- ๐ฆ No dependencies
- ๐ฏ 100% Test coverage
Installing
npm i next-api-compose -S
# or
yarn add next-api-composeBasic usage:
import { compose } from 'next-api-compose'
export default compose([withBar, withFoo], (request, response) => {
const { foo, bar } = request
response.status(200).json({ foo, bar })
})the withBar middleware will append bar property to request object, then withFoo will do accordingly the same but with foo property
Using Express or Connect middleware
If you want to use next-api-compose along with Connect middleware that is widely used eg. in Express framework, there is special utility function for it.
import { compose, convert } from 'next-api-compose'
import helmet from 'helmet'
const withHelmet = convert(helmet())
export default compose([withBar, withFoo, withHelmet], (request, response) => {
const { foo, bar } = request
response.status(200).json({ foo, bar })
})in this example, popular middleware helmet is converted using utility function from next-api-compose and passed as one element in middleware chain
Examples
You can find more examples here:
- JavaScript
- TypeScript
the example/ directory contains simple Next.js application implementing next-api-compose . To fully explore examples implemented in it by yourself - simply do cd examples && npm i && npm run dev then navigate to http://localhost:3000/
Caveats
You may need to add
export const config = { api: { externalResolver: true } }to your Next.js API route configuration in order to dismiss false positive about stalled API requests.
Discussion about this can be found on the Next.js GitHub repository page.If you are using TypeScript and strict types (no
anyat all), you may want to use Partialtype NextApiRequestWithFoo = NextApiRequest & Partial<{ foo: string }>when extending API Route parameters' objects to avoid type errors during usage of
compose.
License
This project is licensed under the MIT license.
All contributions are welcome.