nextjs-api-method-router
v0.1.2
Published
Routing by request method
Downloads
3
Readme
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
);