Using HTTP "Delete" method in REST API on Vercel

We can use HTTP DELETE method instead of POST to implement deleting of data from a database in a REST API. This allows us to implement CRUD operations using a single API endpoint. Since HTML forms have no support for delete method, we should use JavaScript to send a delete request to server. Note that such requests should not have a body, so we provide an empty body to avoid browsers like Chrome throwing an error.

fetch(`/api/endpoint/${post_id}`, {
   method: 'DELETE',
   body: JSON.stringify({})
});

Then on the server the request can be processed like this:

import { ObjectId } from 'mongodb';

// code removed for sake of simplicity

const deleteDocument = async (request, collection) => {
  if (request.method === 'DELETE') {
    const query = {_id: new ObjectId(request.query.post_id)};
    const result = await collection.deleteOne(query);
    console.log(result.deletedCount);
  }
};

To make sure that post_id is received as a query in backend, we need to provide a rewrite rule in vercel.json:

{
    "rewrites": [
      {
        "source": "/api/endpoint/:post_id",
        "destination": "/api/endpoint"
      }
    ]
}