DEV Community

Rishabh Jain
Rishabh Jain

Posted on

How to handle same endpoints with different http methods ??

Suppose a endpoint in nextjs like /api/events
and corresponding directory must be like /pages/api/events.js

If i send request at /api/events with get method, it will run say handler1

If i send request at /api/events with post method, it will run say handler2

Don't know, How to do this ??

Top comments (2)

Collapse
 
brense profile image
Rense Bakker

From the nextjs documentation nextjs.org/docs/api-routes/introdu...

To handle different HTTP methods in an API route, you can use req.method in your request handler, like so:

export default function handler(req, res) {
  if (req.method === 'POST') {
    // Process a POST request
  } else {
    // Handle any other HTTP method
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
brense profile image
Rense Bakker

Someone actually just made a really good post about this problem: dev.to/jussinevavuori/smarter-next...