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