PATCH request handlers
This page explains how to implement PATCH request handlers in Next.js for updating resources.
Understanding PATCH requests
PATCH requests enable partial modifications to a resource. Unlike PUT requests that replace an entire resource, PATCH requests update only specified fields.
Creating a PATCH handler
To handle PATCH requests in a dynamic route:
- Create a dynamic route handler (see Dynamic route handlers)
- Export an async function named
PATCH
- Process the request body and update the resource
export async function PATCH( request: Request, { params }: { params: Promise<{ id: string }> }) { const { id } = await params; const body = await request.json(); const { text } = body;
const index = comments.findIndex((comment) => comment.id === parseInt(id)); comments[index].text = text; return Response.json(comments[index]);}
Request structure
A typical PATCH request includes:
- The resource identifier in the URL (e.g.,
/api/comments/1
) - A JSON body containing the fields to update:
{ "text": "Updated comment"}
Processing PATCH requests
The handler:
- Extracts the resource ID from the route parameters
- Parses the request body to get updated fields
- Finds and updates the resource
- Returns the modified resource
Good to know
- PATCH requests require a dynamic route to identify the resource
- Changes to in-memory data (like arrays) don’t persist after server restart
- Always validate input data and handle potential errors