Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/mathew-horner/next-dispatch-request
Simple library for creating HTTP method specific API route handlers in Next.js
https://github.com/mathew-horner/next-dispatch-request
Last synced: 25 days ago
JSON representation
Simple library for creating HTTP method specific API route handlers in Next.js
- Host: GitHub
- URL: https://github.com/mathew-horner/next-dispatch-request
- Owner: mathew-horner
- Created: 2022-01-21T07:16:46.000Z (almost 3 years ago)
- Default Branch: master
- Last Pushed: 2024-11-12T05:21:03.000Z (2 months ago)
- Last Synced: 2024-11-12T06:23:11.009Z (2 months ago)
- Language: TypeScript
- Size: 1.33 MB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 8
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Next.js API Request Dispatcher
A package to provide a clean way to handle writing discrete method handlers for your Next.js API routes.
# Install
```
npm i next-dispatch-request
```## Usage
A common way to handle different method types in Next.js is to simply branch based on the method:
```ts
export default function handler(req, res) {
if (req.method === 'POST') {
// ... Do POST stuff
} else if (req.method === 'GET') {
// ... Do GET stuff
} else {
res.setHeader('Allow', ['POST', 'GET']);
res.send(405).send('Method Not Allowed!');
}
}
```This package introduces a new pattern to write request handlers for different methods:
```ts
export default createRequestDispatcher({
post(req, res) {
// ... Do POST stuff
},
get(req, res) {
// ... Do GET stuff
}
});
```The function that is returned by `createRequestDispatcher` will handle some of the overhead for you by checking if the method has a corresponding handler, and then calling the handler that maps to the method that the requestor sent in the HTTP request. It also handles sending back a 405 error for methods that have no corresponding handler.