This library provides simple yet complete higher order function
with responsibility of composing multiple middleware functions into one Next.js API route handler in the pages directory router configuration.
Learn more about the
The library does not contain routing utilities. I believe mechanism built in
Next.js itself or next-connect library are sufficient solutions.
- 😇 Simple and powerful API
- 🥷 TypeScript support
- 🧬 Maintaining order of middleware chain
- 🔧 Compatible with Express/Connect middleware
- 💢 Error handling
- 📦 No dependencies
- 💯 100% Test coverage
npm i next-api-compose -S
# or
yarn add next-api-compose
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
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
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/
-
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
any
at 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
.
This project is licensed under the MIT license.
All contributions are welcome.