2.1.1 โ€ข Published 5 months ago

next-api-compose v2.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

Next.js API Compose ยท version codecov CodeFactor npm bundle size

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-compose

Basic 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:

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

  1. 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.

  2. If you are using TypeScript and strict types (no any at all), you may want to use Partial

    type 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.

2.1.1

5 months ago

2.1.0

5 months ago

2.0.0

7 months ago

1.3.1

3 years ago

1.3.0

3 years ago

1.2.0

3 years ago

1.1.1

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago