This library provides many helpful utilities for use in Next.js projects.
This project requires NodeJS (version 8 or later) and NPM. Node and NPM are really easy to install. To make sure you have them available on your machine, try running the following command.
$ npm -v && node -v
6.4.1
v8.16.0
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system.
BEFORE YOU INSTALL: please read the prerequisites
To install and set up the library, run:
$ npm install nextjs-utilities
Or if you prefer using Yarn:
$ yarn add nextjs-utilities
import { catcher, get, post, withMethod, wrapper } from "nextjs-utilities";
interface RequestBody {
name: string;
}
interface ResponseBody {
id: number;
logged_in: boolean;
}
const getHandler = get(
catcher((req, res) => {
throw new Error("This is an error");
res.status(200).json({ name: "Get" });
})
);
const postHandler = post(
wrapper<RequestBody, ResponseBody>((req, res) => {
console.log(typeof req.body); // { name: string }
console.log(typeof res.json); // (body: { id: number; logged_in: boolean; }) => void
})
);
export default withMethod(getHandler, postHandler);
wrapper<Req, Res>(handler: (req: NextAPIRequest & { body: Req }, res: NextAPIResponse<Res>) => void): NextApiHandler
The wrapper
function accepts two generics (if coding in Typescript) and preprocesses and types the request body and response json function. The request body is automatically parsed and coerced into the Req type given.
NOTE To account for type inconsistencies, the query object is instead moved to the body property no matter the type of request, so whether using GET or POST/PUT/DELETE, use req.body
for the information passed to the API route.
Supported options and result fields for the wrapper
function are listed below.
Req
(REQUIRED)
The type of the request body/query (consolidated into a single body
property on the req object).
Res
(REQUIRED)
The type of the response body (used for the json
method on the res object).
handler
(REQUIRED)
The API route logic, with extended request and response objects passed in.
Example:
interface RequestBody {
name: string;
}
interface ResponseBody {
id: number;
logged_in: boolean;
}
wrapper<RequestBody, ResponseBody>((req, res) => {
console.log(typeof req.body); // { name: string }
console.log(typeof res.json); // (body: { id: number; logged_in: boolean; }) => void
});
withMethod(...handlers: NextApiHandler[]): NextApiHandler
The withMethod
function accepts a list of API route handlers and compiles them into one handler that is intended to be the default export of that route. Meant to be used with the following method handlers.
get((req, res) => {
console.log(req.method); // GET
});
Runs the handler provided against a GET method check.
post((req, res) => {
console.log(req.method); // POST
});
Runs the handler provided against a POST method check.
put((req, res) => {
console.log(req.method); // PUT or PATCH
});
Runs the handler provided against a PUT or PATCH method check.
del((req, res) => {
console.log(req.method); // DELETE
});
Runs the handler provided against a DELETE method check.
Supported options and result fields for the withMethod
function are listed below.
...handlers
(REQUIRED)
List of handlers to run in one single exported handler function. Ideally should be a list of method handlers.
Supported options and result fields for all four method handlers are listed below.
handler
(REQUIRED)
The handler to run against the method check
Example:
const getHandler = get((req, res) => {
res.status(200).json({ name: "GET" });
});
const postHandler = post((req, res) => {
res.status(200).json({ name: "POST" });
});
export default withMethod(getHandler, postHandler);
catcher(handler: NextApiHandler, property?: string = "error"): NextApiHandler
The catcher
takes in a handler and wraps it in a try/catch block that will catch any errors thrown in the handler and return a 500 status code with the error message as the response body. The property name for the error message can be changed by passing in a string as the second argument.
Supported options and result fields for the catcher
function are listed below.
handler
(REQUIRED)
The handler to wrap in a try/catch block.
property
(OPTIONAL)
The property name for the error message. Defaults to "error".
Example:
catcher((req, res) => {
throw new Error("Error");
}); // will return a 500 status code with the response body { error: "Error" }
- Fork the repo
- Create your feature branch (
git checkout -b amazing-feature
) - Commit your changes (
git commit -am 'Add some amazing feature'
) - Push to the branch (
git push origin amazing-feature
) - Create a new Pull Request
- Next.js - The web framework used
- TypeScript - The language used
We use SemVer for versioning. For the versions available, see the tags on this repository.
- Snehil Kakani - Creator and Lead Developer - snehilkakani.me
See also the list of contributors who participated in this project.