Sling Academy
Home/Next.js/Next.js 14: Extracting Request Body in Route Handlers

Next.js 14: Extracting Request Body in Route Handlers

Last updated: December 18, 2023

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!

Next Article: Next.js: How to Extract Request Headers (4 Approaches)

Previous Article: Next.js API Routes: How to Get Parameters & Query String

Series: Route Handlers and API Routes in Next.js

Next.js

Related Articles

You May Also Like

  • Solving Next.js Image Component Error with CSS Classes
  • How to Use MUI (Material UI) in Next.js 14
  • Fixing Data Update Issues in Next.js Production
  • Fixing Next.js Undefined ENV Variables in Production Build
  • Solving Next.js SyntaxError: Unexpected token ‘export’
  • Next.js Error: Found Page Without a React Component as Default Export – How to Fix
  • Fixing Next.js Error: Blank Page on Production Build
  • Fixing Next.js Error when Importing SVGs: A Step-by-Step Guide
  • Next.js Issue: useEffect Hook Running Twice in Client
  • Fixing ‘self’ is not defined error in Next.js when importing client-side libraries
  • How to Dockerize a Next.js App for Production
  • How to set up Next.js with Docker Composer and Nginx
  • Solving Next.js CORS Issues: A Comprehensive Guide
  • Fixing Next.js Hydration Mismatch Error in Simple Ways
  • Next.js Error: Cannot use import statement outside a module
  • Next.js: How to Access Files in the Public Folder
  • Fixing Next.js Import CSS Error: A Simple Guide
  • Fixing LocalStorage Not Defined Error in Next.js
  • Fixing Next.js Error: No HTTP Methods Exported