•  


GitHub - neg4n/next-api-compose: ?? Simple, dependency free, error aware and powerful utility to compose chain of multiple middleware into one Next.js API Route.
Skip to content

?? Simple, dependency free, error aware and powerful utility to compose chain of multiple middleware into one Next.js API Route.

License

Notifications You must be signed in to change notification settings

neg4n/next-api-compose

Repository files navigation

next-api-compose example code theme aware

Next.js API Compose · version npm bundle size

Introduction

This library provides a hassle-free way of composing multiple middleware functions into one Next.js API Route Handler 's method in the App Directory router.

Important

The 2.0.0 version of the library supports both app and pages directory oriented API utilities. If you're still using Pages Router and you want to migrate from versions below 2.0.0 , please read migration guide and ocassionally consider checking out intro to the App Router .

Features

  • ?? Simple and powerful API
  • ?? Designed both for Pages Router and App Router
  • ?? Production-ready. 100% test coverage, even type inference is tested!
  • ?? Excellent TypeScript support
  • ?? Maintaining order of middleware chain
  • ?? No dependencies, small footprint

Installing and basic usage

Install the package by running:

npm i next-api-compose -S
#
 or

yarn add next-api-compose
#
 or

pnpm i next-api-compose

then create an API Route Handler in the App Directory :

in TypeScript (recommended)

import
 type
 {
 NextRequest
 }
 from
 "next/server"
;

import
 {
 compose
 }
 from
 "next-api-compose"
;


function
 someMiddleware
(
request
: 
NextRequest
 &
 {
 foo
: 
string
 }
)
 {

  request
.
foo
 =
 "bar"
;

}


const
 {
 GET
 }
 =
 compose
(
{

  GET
: 
[

    [
someMiddleware
]
,

    (
request
 /* This is automatically inferred */
)
 =>
 {

      return
 new
 Response
(
request
.
foo
)
;

      //                         ^ (property) foo: string - autocomplete works here

    }
,

  ]
,

}
)
;


export
 {
 GET
 }
;

in JavaScript:

import
 {
 compose
 }
 from
 "next-api-compose"
;


function
 someMiddleware
(
request
)
 {

  request
.
foo
 =
 "bar"
;

}


const
 {
 GET
 }
 =
 compose
(
{

  GET
: 
[

    [
someMiddleware
]
,

    (
request
)
 =>
 {

      return
 new
 Response
(
request
.
foo
)
;

    }
,

  ]
,

}
)
;


export
 {
 GET
 }
;

Error handling

Handling errors both in middleware and in the main handler is as simple as providing sharedErrorHandler to the compose function's second parameter (a.k.a compose settings) . Main goal of the shared error handler is to provide clear and easy way to e.g. send the error metadata to Sentry or other error tracking service.

By default, shared error handler looks like this:

sharedErrorHandler: 
{

  handler: 
undefined
;

  // ^^^^ This is the handler function. By default there is no handler, so the error is being just thrown.

  includeRouteHandler: 
false
;

  // ^^^^^^^^^^^^^^^^ This toggles whether the route handler itself should be included in a error handled area.

  //                  By default only middlewares are being caught by the sharedErrorHandler

}

... and some usage example:

// [...]

function
 errorMiddleware
(
)
 {

  throw
 new
 Error
(
"foo"
)
;

}


const
 {
 GET
 }
 =
 compose
(

  {

    GET
: 
[

      [
errorMiddleware
]
,

      (
)
 =>
 {

        // Unreachable code due to errorMiddleware throwing an error and halting the chain

        return
 new
 Response
(
JSON
.
stringify
(
{
 foo
: 
"bar"
 }
)
)
;

      }
,

    ]
,

  }
,

  {

    sharedErrorHandler
: 
{

      handler
: 
(
_method
,
 error
)
 =>
 {

        return
 new
 Response
(
JSON
.
stringify
(
{
 error
: 
error
.
message
 }
)
,
 {

          status
: 
500
,

        }
)
;

      }
,

    }
,

  }

)
;

// [...]

will return {"error": "foo"} along with 500 status code instead of throwing an error.

Theory and caveats

  1. Unfortunately there is no way to dynamically export named ESModules (or at least I did not find a way) so you have to use export { GET, POST } syntax instead of something like export compose(...) if you're composing GET and POST methods :(

  2. Middleware is executed as specified in the per-method array, so if you want to execute middleware in a specific order, you have to be careful about it. Early returned new Response() halts the middleware chain.

Contributors

Igor
Igor

?? ?? ??
Maksymilian Grabka
Maksymilian Grabka

?? ??
kacper3123
kacper3123

??

License and acknowledgements

The project is licensed under The MIT License. Thanks for all the contributions! Feel free to open an issue or a pull request even if it is just a question ??

- "漢字路" 한글한자자동변환 서비스는 교육부 고전문헌국역지원사업의 지원으로 구축되었습니다.
- "漢字路" 한글한자자동변환 서비스는 전통문화연구회 "울산대학교한국어처리연구실 옥철영(IT융합전공)교수팀"에서 개발한 한글한자자동변환기를 바탕하여 지속적으로 공동 연구 개발하고 있는 서비스입니다.
- 현재 고유명사(인명, 지명등)을 비롯한 여러 변환오류가 있으며 이를 해결하고자 많은 연구 개발을 진행하고자 하고 있습니다. 이를 인지하시고 다른 곳에서 인용시 한자 변환 결과를 한번 더 검토하시고 사용해 주시기 바랍니다.
- 변환오류 및 건의,문의사항은 juntong@juntong.or.kr로 메일로 보내주시면 감사하겠습니다. .
Copyright ⓒ 2020 By '전통문화연구회(傳統文化硏究會)' All Rights reserved.
 한국   대만   중국   일본