PATCH is used for partial updates. You only send the fields you want to change, not the entire resource.
How PATCH Works
Now we’ll use app.patch() to create routes that handle PATCH requests.
From the frontend:
fetch("/users/1", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: "newemail@example.com" }),
});
On the API side:
app.patch("/users/:id", (req, res) => {
const userId = Number(req.params.id);
// Check if ID is a valid number
if (isNaN(userId)) {
return res.status(400).json({ error: "Invalid user ID" });
}
const updates = req.body;
// Find the user
const userIndex = users.findIndex((user) => user.id === userId);
if (userIndex === -1) {
return res.status(404).json({ error: "User not found" });
}
// Update only the provided fields
users[userIndex] = { ...users[userIndex], ...updates };
res.json(users[userIndex]);
});
Key Points About PATCH
- Partial updates - Only send the fields you want to change
- Spread operator -
{ ...existing, ...updates }merges objects - Keep existing data - Fields not in the request stay the same
- Same URL structure - Uses
:idparameter like PUT
How the spread operator works:
// If existing user is: { id: 1, name: "John", email: "john@example.com" }
// And updates is: { email: "newemail@example.com" }
// Result: { id: 1, name: "John", email: "newemail@example.com" }
The spread operator (...) copies all properties from the existing object, then the updates object overwrites any matching properties. This keeps unchanged fields and updates only the new ones.
PUT vs PATCH
- PUT - Replace entire resource (all fields required)
- PATCH - Update specific fields (only changed fields needed)
PUT is like submitting a new profile form that replaces the old one entirely. You have to fill out every field again, even if you only want to change your email.
PATCH is like editing just your email or name without touching the rest. You only update the fields you want to change.
Security note: In a real application, this route would also require proper authentication and authorization, which we’ll cover in Module 3.