npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

next-hdlr

v1.0.1

Published

Next.js API route handler wrapper for simplifying HTTP request methods.

Downloads

20

Readme

Next-Hdlr

A HTTP route method utility for Next.js 12 api handlers.

Use Case

Do you often find yourself creating large switch statements when creating a new API in Next.js?

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { method } = req;

  try {
    switch (method) {
      case "GET":
        await GET(req, res);
        break;
      case "POST":
        await POST(req, res);
        break;
      case "PATCH":
        await PATCH(req, res);
        break;
      case "PUT":
        await PUT(req, res);
        break;
      case "DELETE":
        await DELETE(req, res);
        break;
      default:
        res.setHeader("Allow", ["GET", "POST", "PATCH", "PUT", "DELETE"]);
        return res
          .status(ResponseStatus.MethodNotAllowed)
          .send("Method Not Allowed");
    }
  } catch (e: any) {
    return res
      .status(ResponseStatus.InternalServerError)
      .send("Internal Server Error");
  }
}

// Handlers ...

If so, Next-Hdlr Is the perfect utility for you, as you can take all that boiler plate and narrow it down to:

const handler = new RouteHandler();

// method handlers ...
handler.GET((req, res) => {});

handler.POST((req, res) => {});

handler.PATCH((req, res) => {});

handler.PUT((req, res) => {});

handler.DELETE((req, res) => {});

export default handler.build();

Ahh yes, much cleaner 🥤

Basic Usage

Let's take a look at how to use Next-Hdlr for your next or current project.

Install

First you will need to add it to your project. Next-Hdlr only supports Next.js versions 9.0.0 and up.

npm i next-hdlr

Creating a Route Handler

You can configure individual routes using the RouteHandler class. This class allows you to define handlers for different HTTP methods like GET, POST, PUT, PATCH, and DELETE.

Here’s how you set up a simple API handler within the /pages/api directory:

import { Handler } from "next-hdlr";

const handler = new RouteHandler();

// Define endpoints
handler.GET((req, res) => {
  res.status(200).json({ message: "GET request success" });
});

handler.POST((req, res) => {
  res.status(201).json({ message: "POST request success" });
});

Exporting Your Handler

After defining all the routes, use the build() method to create your route handler:

export default handler.build();

TypeScript

To leverage intellisense and improve the DX, pass your expected type to the method handler. This way, you can take full advantage of TypeScript's powerful type inference.

interface POSTRequestPayload {
  data: string;
}

interface POSTResponsePayload {
  message: string;
}

handler.POST<POSTPayload, POSTResponsePayload>((req, res) => {
  console.log(req.body.data);

  res.status(200).json({ message: "`data` is defined!" });
});

Please note that methods GET and DELETE only take a response generics while methods POST, PATCH, and PUT have both request and response payload generics. See RFC 7231.

Issues

If you find that something is not right with the API please create a new issue. Contributions are also welcome!