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:
- Create an API Route File:
- First, create a new file under the
pages/apidirectory of your Next.js project. The file name will determine the path of the API route. For example, creating a file namedexample.jsunderpages/apiwill create an API route accessible at/api/example. - 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
handlerfunction checks thereq.methodproperty to determine which HTTP method was used in the request. - Depending on the HTTP method, different logic is executed inside each
ifblock. - For each method (
GET,POST,PUT,DELETE), a specific response is sent back to the client usingres.status().json()to set the HTTP status code and send a JSON response.