Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save mixdev/8e45e9652d0018ed07f5d57cb645daf9 to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

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