Utilities library built on top of Next.js providing feature extensions and helpers for common patterns

Overview

npm version code style: prettier

nextjs-utilites

This library provides many helpful utilities for use in Next.js projects.

Prerequisites

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

Table of contents

Getting Started

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.

Installation

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

Example Usage

API Route 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);

API

wrapper

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

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

get((req, res) => {
  console.log(req.method); // GET
});

Runs the handler provided against a GET method check.

post

post((req, res) => {
  console.log(req.method); // POST
});

Runs the handler provided against a POST method check.

put

put((req, res) => {
  console.log(req.method); // PUT or PATCH
});

Runs the handler provided against a PUT or PATCH method check.

delete

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

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" }

Contributing

  1. Fork the repo
  2. Create your feature branch (git checkout -b amazing-feature)
  3. Commit your changes (git commit -am 'Add some amazing feature')
  4. Push to the branch (git push origin amazing-feature)
  5. Create a new Pull Request

Built With

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

Authors

See also the list of contributors who participated in this project.

You might also like...

The CryptoVerse is a Cryptocurrency web application developed using Reactjs for providing the latest updates, value statistics, market cap, supply and news regarding the Cryptocurrency market.

The CryptoVerse is a Cryptocurrency web application developed using Reactjs for providing the latest updates, value statistics, market cap, supply and news regarding the Cryptocurrency market.

CryptoVerse - A Crptocurrency Web Application Getting Started with Create React App This project was bootstrapped with Create React App. Available Scr

Oct 26, 2022

A npm package to increase the developer experience and consistency by providing a set of hooks that can be opted-in the development lifecycle.

@jeliasson/husky-hooks This npm package aims to increase the developer experience and consistency by providing a set of hooks that can be opted-in the

Dec 6, 2022

Providing accessible components with Web Components & Material You

tiny-material Still on developing, DO NOT use for production environment Run well on Google Chrome, Firefox, Chrome for Android, Microsoft Edge (Chrom

Dec 31, 2022

🐐 Simple and complete React DOM testing utilities that encourage good testing practices.

🐐 Simple and complete React DOM testing utilities that encourage good testing practices.

React Testing Library Simple and complete React DOM testing utilities that encourage good testing practices. Read The Docs | Edit the docs Table of Co

Jan 4, 2023

JavaScript Testing utilities for React

Enzyme Enzyme is a JavaScript Testing utility for React that makes it easier to test your React Components' output. You can also manipulate, traverse,

Dec 28, 2022

A collection of framework specific Auth utilities for working with Supabase.

A collection of framework specific Auth utilities for working with Supabase.

Jan 2, 2023

A frontend Framework for building B2B applications running in the browser on top of REST/GraphQL APIs, using ES6, React and Material Design

A frontend Framework for building B2B applications running in the browser on top of REST/GraphQL APIs, using ES6, React and Material Design

react-admin A frontend Framework for building data-driven applications running in the browser on top of REST/GraphQL APIs, using ES6, React and Materi

Dec 30, 2022

Based on pure JS scripts, without relying on native, no need for react-native link, Title / Header / Tabs / Sticky / Screen components can be flexibly configured, among which Tabs / Sticky can slide When it reaches the top, it will be topped.

Based on pure JS scripts, without relying on native, no need for react-native link, Title / Header / Tabs / Sticky / Screen components can be flexibly configured, among which Tabs / Sticky can slide When it reaches the top, it will be topped.

react-native-scrollable-tabview English | 简体中文 Based on pure JS scripts, without relying on native, no need for react-native link,Title / Header / Tab

Dec 30, 2022

Buy or renew two-wheeler insurance online. Free Quotes from Top Insurers with Lowest Premiums in 20 Seconds

Buy or renew two-wheeler insurance online. Free Quotes from Top Insurers with Lowest Premiums in 20 Seconds

PolicyBazaar Clone This project was created using create-react-app and Json server How to run app Clone the app git clone url How to run backend npm

Nov 17, 2022
Owner
Snehil K
15 year old professional full stack web developer, actor, and drummer at Lynbrook High School
Snehil K
Common React Native components used by "Roqay" packed in library for usage in future projects.

Roqay Common React Native Components Common React Native components used by Roqay packed in library for usage in future projects. Installation yarn ad

RoQay 3 Feb 10, 2022
A free book that talks about design patterns/techniques used while developing with React.

React in patterns ?? A free book that talks about design patterns/techniques used while developing with React. Book GitBook Web PDF Mobi ePub Translat

Krasimir Tsonev 12.3k Jan 7, 2023
Set of property utilities for Stitches with theme tokens support. Use the built-in utils, or easily build custom ones.

Stitches Mix Set of property utilities for Stitches with theme tokens support. Use the built-in utils, or easily build custom ones. Usage To import al

João Pedro Schmitz 12 Aug 8, 2022
nivo provides a rich set of dataviz components, built on top of the awesome d3 and Reactjs libraries

nivo provides supercharged React components to easily build dataviz apps, it's built on top of d3. Several libraries already exist for React d3 integr

Raphaël Benitte 10.9k Dec 31, 2022
Juka Official Website built on top of Docusaurus/React Framework. Help us make it better!

Juka Programming Language Juka Programming Language website is built on top of Docusaurus 2. Feel free to contribute to our website! Any help is appre

Juka Programming Language 5 Dec 24, 2022
Recipe providing mobile app, User selects ingredients in pantry and is then provided recipes for those ingredients. App contains a signup/login, meal planner and grocery list pages.

Recipog Student Information Name Connor de Bruyn Username Destiro Assignment SWEN325 A2 Description “Recipog” is a recipe providing app that allows th

Connor de Bruyn 1 Dec 26, 2021
A weather app done with React. Allows you to make a search for the current weather by simply typing "common knowledge" cities and save them to favourites on local storage.

Simpliest Weather React-App A weather app done with React. Allows you to make a search for the current weather by simply typing "common knowledge" cit

Larry Noriega 3 Aug 24, 2022
a more intuitive way of defining private, public and common routes for react applications using react-router-dom v6

auth-react-router is a wrapper over react-router-dom v6 that provides a simple API for configuring public, private and common routes (React suspense r

Pasecinic Nichita 12 Dec 3, 2022
Common recipes to productively use Nx with various technologies and in different setups. Made with ❤️ by the Nx Team

Nx Recipes Welcome to Nx Recipes! Here you'll find various examples to use Nx to achieve a particular goal. Contributing Absolutely!! We're going to h

Nrwl 30 Dec 24, 2022
Further split the React Native code based on Metro build to improve performance, providing `Dll` and `Dynamic Imports` features

React-Native Code Splitting Further split the React Native code based on Metro build to improve performance, providing Dll and Dynamic Imports feature

Wuba 126 Dec 29, 2022