nextjs-api-method-router
TypeScript icon, indicating that this package has built-in type declarations

0.1.2 • Public • Published

nextjs-api-method-router

Plain

type Response = { method: string } | { errorMsg: string };

const handler: NextApiHandler<Response> = (req, res) => {
  switch (req.method) {
    case "GET":
      res.status(200).json({ method: "get" });
      break;
    case "POST":
      res.status(200).json({ method: "post" });
      break;
    default:
      res.status(405).json({ errorMsg: "Not allowed" });
  }
};

export default handler;

With nextjs-api-router

import { routeByRequestMethod } from "nextjs-api-method-router";

type GetResponse = { method: "get" };
type PostResponse = { method: "post" };

const getHandler = (req, res) => {
  res.status(200).json({ method: "get" });
};

const postHandler = (req, res) => {
  res.status(200).json({ method: "post" });
};

const otherHandler = (req, res) => {
  res.status(405).json({ errorMsg: "Not allowed" });
};

export default routeByRequestMethod(
  {
    GET: getHandler,
    POST: postHandler,
  },
  otherHandler
);

/nextjs-api-method-router/

    Package Sidebar

    Install

    npm i nextjs-api-method-router

    Weekly Downloads

    1

    Version

    0.1.2

    License

    MIT

    Unpacked Size

    7.59 kB

    Total Files

    20

    Last publish

    Collaborators

    • mkanenobu