Partial Updates with PATCH

Introduction: Why PATCH?

Welcome to the final lesson of this course! So far, you have learned how to create, fetch, update, and delete user data using different HTTP methods in Next.js API routes. In this lesson, we will focus on the PATCH method.

PATCH is used when you want to update only part of a resource, not the whole thing. This is different from PUT, which usually replaces the entire resource with new data. PATCH is helpful when you only want to change a few fields, such as updating just a user's email or name, without affecting the rest of their information.

For example, if you have a user profile and only want to update the user's email address, PATCH lets you do that without sending all the other user details again.

How PATCH Works: Partial Updates In Action

PATCH is all about making partial updates. Think of it like editing a form: if you only want to change your phone number, you don’t need to rewrite your whole profile — just update the phone number field.

When you send a PATCH request, you include only the fields you want to change. The server then updates just those fields, leaving everything else as it was.

For example, if a user has this data:

{
  "id": 1,
  "name": "Alice",
  "email": "alice@example.com"
}

And you send a PATCH request with:

{
  "email": "alice.new@example.com"
}

The server will update only the email field. The name stays the same.

PUT vs PATCH: Why They’re Not Interchangeable

Both PUT and PATCH can be used to update data, but they behave differently:

  • PUT replaces the entire object with a new one. If you forget to include a field, it may get wiped out.
  • PATCH only updates the fields you provide, leaving all other data untouched.

Use PATCH when:

  • You want to change only a few fields (e.g., just the email) = You want to avoid sending large payloads repeatedly

Use PUT when:

  • You want to reset the entire object
  • You can guarantee the full object will always be sent in the request

Step-by-Step: Writing a PATCH Handler in Next.js

Let’s look at how to implement PATCH in our Next.js API route. Here’s the relevant part of the code:

export async function PATCH(request: NextRequest, { params }: RouteParams) {
  const userId = parseInt(params.id, 10);
  const userIndex = users.findIndex((u) => u.id === userId);

  if (userIndex === -1) {
    return NextResponse.json({ error: 'User not found' }, { status: 404 });
  }

  const partialUpdate = await request.json();

  // Merge the update into the existing user
  users[userIndex] = {
    ...users[userIndex],
    ...partialUpdate,
  };

  return NextResponse.json(users[userIndex]);
}

Let’s break this down:

  • Find the User:
    The code gets the user ID from the URL and looks for the user in the users array.

    const userId = parseInt(params.id, 10);
    const userIndex = users.findIndex((u) => u.id === userId);

    If the user is not found, it returns a 404 error.

  • Read the Update Data:
    The code reads the JSON body of the request, which contains the fields to update.

    const partialUpdate = await request.json();
  • Merge the Update:
    The code uses the spread operator (...) to merge the existing user data with the new fields. This means only the fields you send in the PATCH request will be updated.

    users[userIndex] = {
      ...users[userIndex],
      ...partialUpdate,
    };
  • Return the Updated User:
    Finally, the updated user is returned as a JSON response.

Example Output:
If you PATCH /api/users/1 with { "email": "alice.new@example.com" }, the response will be:

{
  "id": 1,
  "name": "Alice",
  "email": "alice.new@example.com"
}

🧠 Additionally, you may want to add a validation step here to ensure the update only contains allowed fields (e.g., "name" and "email"). In real applications, accepting arbitrary keys could lead to users injecting unwanted data into your system. For example:

const allowedFields = ['name', 'email'];
const isValid = Object.keys(partialUpdate).every(key => allowedFields.includes(key));

if (!isValid) {
  return NextResponse.json({ error: 'Invalid fields in update' }, { status: 400 });
}

You'll have a chance to implement this in one of the upcoming practices! 😊


Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal