Updating and Deleting Users
Introduction: Why Update and Delete?
Welcome back! So far, you have learned how to create new users with POST and fetch a single user with a GET request. In real-world applications, it is just as important to be able to update and delete data. For example, users might want to edit their profile information or remove their account entirely. In this lesson, you will learn how to handle these actions using the PUT and DELETE methods in a Next.js API route.
By the end of this lesson, you will know how to update a user’s information and remove a user from your data store. These are essential skills for building any full-featured backend.
Recap: Our API Route and Data Setup
Before we dive into updating and deleting, let’s quickly remind ourselves of the setup we have been using. We have a simple array of users and a dynamic API route that handles requests for a specific user by their ID.
Here is a quick look at the setup:
usersis our in-memory array that stores user objects.- The route uses a dynamic segment
[id]to handle requests for a specific user.
This setup allows us to easily find a user by their ID.
PUT Method: Updating a User
The PUT method is used to update an existing resource. In our case, it lets us update a user’s details. Let’s look at the code for handling a PUT request:
Let’s break this down:
- We get the user
IDfrom the URL and look for the user in our array. - If the user is not found, we return a 404 error with a message.
- If the user exists, we read the new data from the request body.
- We update the user’s information in the array, keeping the same
ID. - Finally, we return the updated user as a JSON response.
Example:
Suppose you send a PUT request to /api/users/2 with this JSON body:
If user 2 exists, the response will be:
If user 2 does not exist, you will get:
with a status code of 404.
⚠️ Important: This implementation assumes you're replacing the entire user object (except for the id). If the client sends only a partial object (e.g., just a "name" field), the email will be lost. This is how the PUT method works: it's designed to fully replace the resource, not partially update it.
For example, sending:
would result in this:
In a real application, you'd either:
- Require all fields on every PUT, or
- Use
PATCHif you want to allow partial updates (we’ll explore this in later units).
For now, just remember: if you're using PUT, send all fields the user should have.
