How to Handle Different HTTP Verbs in a Next.js API Route

In a Next.js API route, you can handle different HTTP verbs (methods) such as GET, POST, PUT, DELETE, etc., by using the appropriate request handler functions exported from the file corresponding to your API route. Each HTTP verb corresponds to a specific request handler function that you can export from your API route file.

Here’s how you can handle different HTTP verbs in a Next.js API route:

  1. Create an API Route File:
  2. First, create a new file under the pages/api directory of your Next.js project. The file name will determine the path of the API route. For example, creating a file named example.js under pages/api will create an API route accessible at /api/example.
  3. Define Request Handlers:
In the API route file, you can define different request handlers based on the HTTP method you want to handle (GET, POST, PUT, DELETE, etc.). Each request handler receives two parameters: req (the incoming request object) and res (the response object). You can use these parameters to access request data and send a response back to the client.
  • The handler function checks the req.method property to determine which HTTP method was used in the request.
  • Depending on the HTTP method, different logic is executed inside each if block.
  • For each method (GET, POST, PUT, DELETE), a specific response is sent back to the client using res.status().json() to set the HTTP status code and send a JSON response.

Leave a comment

Your email address will not be published. Required fields are marked *