Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mixdev/8e45e9652d0018ed07f5d57cb645daf9 to your computer and use it in GitHub Desktop.
Save mixdev/8e45e9652d0018ed07f5d57cb645daf9 to your computer and use it in GitHub Desktop.
//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);
@Hoxtygen
Copy link

Hoxtygen commented Jan 9, 2023

Thanks. Solved my problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment