Profile picture

Software Engineer (Open Source, Dev Tools) at BoxyHQ.

Follow me on Twitter

Next.js - API Route Handler

August 11, 2022

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,
  })
}

Kiran K