Next.js - API Route Handler

Next.js API Route Handler boilerplate.

import type { NextApiRequest, NextApiResponse } from "next";

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

  switch (method) {
    case "GET":
      return handleGET(req, res);
    case "POST":
      return handlePOST(req, res);
    default:
      res.setHeader("Allow", ["GET", "POST"]);
      res.status(405).json({
        data: null,
        error: { message: `Method ${method} Not Allowed` },
      });
  }
}

const handleGET = async (req: NextApiRequest, res: NextApiResponse) => {
  return res.status(200).json({
    data: {},
    error: null,
  });
};

const handlePOST = async (req: NextApiRequest, res: NextApiResponse) => {
  return res.status(200).json({
    data: {},
    error: null,
  });
};