Finally, let’s create an endpoint to delete users.

Unlike the other operations which return the user object, DELETE returns no content - the standard response is 204 No Content, which tells the frontend “the operation succeeded, but there’s no data to send back.”

Deleting Users Endpoint

// Delete a user
app.delete("/users/:id", async (req, res) => {
  try {
    const userId = Number(req.params.id);

    // Validate ID
    if (isNaN(userId)) {
      return res.status(400).json({
        error: "Invalid user ID",
      });
    }

    // Delete the user from the database
    const [result]: [ResultSetHeader, any] = await pool.execute(
      "DELETE FROM users WHERE id = ?",
      [userId]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({
        error: "User not found",
      });
    }

    // Return 204 No Content - successful deletion with no response body
    res.status(204).send();
  } catch (error) {
    console.error("Database error:", error);
    res.status(500).json({
      error: "Failed to delete user",
    });
  }
});

Understanding the DELETE Code

SQL DELETE

  • DELETE FROM users WHERE id = ? removes the user record from the database.
  • Uses WHERE clause to target the specific user by ID.
  • Uses userId from the URL parameter (like PUT and PATCH).

Understanding the Database Result

const [result]: [ResultSetHeader, any] = await pool.execute(
  "DELETE FROM users WHERE id = ?",
  [userId]
);

The DELETE operation returns a ResultSetHeader:

  • affectedRows - How many rows were deleted (0 means user not found, 1 means success).

Response Pattern

  • 204 No Content: Standard status for successful deletion with no response body.
  • 404 Not Found: If the user ID doesn’t exist (result.affectedRows === 0).
  • No data returned: Unlike POST/PUT/PATCH, we don’t send back the deleted user.

Why No Response Body

  • The user is deleted, so there’s nothing meaningful to return.
  • 204 status code tells the frontend “operation succeeded, no content to show”.
  • Frontend can remove the user from its display without needing confirmation data.


Repo link

Tags: