Forked from KolbySisk/nextjs-handler-allow-methods-middleware.ts
Last active
January 9, 2023 11:10
-
-
Save mixdev/8e45e9652d0018ed07f5d57cb645daf9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//file: ./pages/api/checkHTTPMethod.ts | |
/* this code will allow only GET method requests on this route */ | |
import { Middleware, use } from 'next-api-route-middleware'; | |
import type { NextApiRequest, NextApiResponse } from 'next'; | |
export const allowMethods = (allowedMethods: string[]): Middleware => { | |
return async function (req, res, next) { | |
if (allowedMethods.includes(req.method!) || req.method == 'OPTIONS') { | |
next(); | |
} else { | |
res.status(405).send({ message: 'Method not allowed.' }); | |
} | |
}; | |
}; | |
const handler: any = (req: NextApiRequest, res: NextApiResponse) => { | |
res.status(200).send({ message: 'Voila! No error!' }); | |
} | |
export default use(allowMethods(['GET']), handler); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. Solved my problem.