Next.js 14: Extracting Request Body in Route Handlers

Updated: December 18, 2023 By: Khue Post a comment

Next.js 13 and 14 have revolutionized the way we build server-side applications. One key feature is the ability to define route handlers, which are akin to a personalized reception desk for your incoming API requests. One of the common tasks you may want to perform in a Route Handler is to extract the request body, which contains the data sent by the client in a POST, PUT, PATCH, or DELETE request. In this article, I will show you how to access the request body in a Route Handler using the NextRequest and Response objects.

Extracting Request Body in Route Handlers

To create a Route Handler, you need to define a route.js or route.ts file inside the /app directory, and export a function named after the HTTP method you want to handle, such as GET, POST, PUT, etc.

Here’s the main point of this tutorial: To access the request body, you need to use the NextRequest object, which is an extension of the native Request object. The NextRequest object has a json() method that returns a promise that resolves to the parsed JSON object from the request body.

After accessing and doing something with the body of the incoming request, you might want to return a response. In order to do so, you need to use the Response or NextResponse object, which are extensions of the native Response object. The Response object has a json() method that returns a response with the given JSON object as the body.

Here is an example of a Route Handler that extracts the request body and returns it as a JSON response:

// app/api/route.ts
import { NextRequest, NextResponse } from 'next/server';

export async function POST(request: NextRequest) {
  // get the request body as a JSON object
  const body = await request.json();

  // log the body to the console
  console.log({ body });

  // return the body as a JSON response
  return Response.json({ body });
}

To test the Route Handler, you can use a tool like Postman or curl to send a POST request to the /api route with some JSON data in the body. For example, using curl, you can run the following command in a terminal:

curl -X POST -H "Content-Type: application/json" -d '{"name": "Sling Academy", "age": 999}' http://localhost:3000/api

Output:

{"body":{"name":"Sling Academy","age":999}}

Final Words

I have shown you how to extract the request body in Route Handlers in Next.js 14 using the NextRequest and Response objects. I hope this helps you with your project. If you have any questions or feedback, please let me know by leaving a comment. Happy coding & have a nice day with Next.js!