0
0
ExpressHow-ToBeginner · 3 min read

How to Use app.patch in Express for Partial Updates

Use app.patch(path, handler) in Express to define a route that handles HTTP PATCH requests, which are used to partially update resources. The handler function receives the request and response objects to process the update and send a response.
📐

Syntax

The app.patch method defines a route for HTTP PATCH requests. It takes two main parts:

  • path: The URL path to match (e.g., '/user/:id').
  • handler: A function that runs when a PATCH request matches the path. It receives req (request) and res (response) objects.

This method is used to update parts of a resource without replacing the entire resource.

javascript
app.patch(path, (req, res) => {
  // handle partial update
});
💻

Example

This example shows how to use app.patch to update a user's email partially. It listens for PATCH requests at /user/:id, updates the email if provided, and sends back the updated user data.

javascript
import express from 'express';
const app = express();
app.use(express.json());

// Sample user data
const users = {
  '1': { id: '1', name: 'Alice', email: 'alice@example.com' },
  '2': { id: '2', name: 'Bob', email: 'bob@example.com' }
};

app.patch('/user/:id', (req, res) => {
  const userId = req.params.id;
  const user = users[userId];
  if (!user) {
    return res.status(404).json({ error: 'User not found' });
  }

  // Update only the fields sent in the request body
  if (req.body.email) {
    user.email = req.body.email;
  }

  res.json({ message: 'User updated', user });
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000
⚠️

Common Pitfalls

Common mistakes when using app.patch include:

  • Not parsing JSON body with express.json(), causing req.body to be undefined.
  • Trying to replace the entire resource instead of partially updating it.
  • Not checking if the resource exists before updating, leading to errors.
  • Using app.put when only partial updates are needed.

Always validate input and handle missing resources gracefully.

javascript
/* Wrong: Missing express.json() middleware causes req.body to be undefined */
import express from 'express';
const app = express();

app.patch('/item/:id', (req, res) => {
  // req.body will be undefined without express.json()
  res.send(req.body);
});

/* Right: Use express.json() to parse JSON body */
app.use(express.json());
📊

Quick Reference

app.patch(path, handler) is used to handle HTTP PATCH requests for partial updates.

  • path: URL pattern to match.
  • handler: Function with req and res to process the request.
  • Use express.json() middleware to parse JSON request bodies.
  • Check if the resource exists before updating.
  • Send appropriate HTTP status codes (e.g., 404 if not found).

Key Takeaways

Use app.patch to handle HTTP PATCH requests for partial updates in Express.
Always include express.json() middleware to parse JSON request bodies.
Check if the resource exists before attempting to update it.
Update only the fields provided in the request body to avoid overwriting data.
Send clear responses with appropriate HTTP status codes.