How to read request body and query params in next 13's API with app router in route.ts file? – Next.js

by
Ali Hasan
next.js next.js13

Quick Fix: In NextJS 13, you can read query params and request’s body in route.ts using the following code:

import url from 'URL';

export async function POST(request: Request) {
  const requestBody = await request.json(); // To read request data
  const queryParams = url.parse(request.url, true).query;  // To read query params
  return NextResponse.json({requestBody, queryParams});
}

The Solutions:

Solution 1: Using `request.json()` and `url.parse()`.

In Next.js 13, you can read the request body and query parameters using the request.json() and url.parse() methods in the route.ts file. The code snippet below demonstrates how to do this:

import url from "URL";

export async function POST(request: Request) {
  const requestBody = await request.json(); // To read request data

  const queryParams = url.parse(request.url, true).query; // To read query params

  // Returning the query params & body
  return NextResponse.json({
    requestBody,
    queryParams,
  });
}

In this code:

  1. The request.json() method parses the request body as JSON and returns a JavaScript object.

  2. The url.parse() method takes the request’s URL as an argument and returns an object with various parts of the URL, including the query parameters. The true argument specifies that the query parameters should be parsed as an object.

  3. The NextResponse.json() method creates a JSON response object with the request body and query parameters.

Solution 2: NextJS 13 with app router in route.ts file

In NextJS 13, you can use the URL class to read the query parameters in **app/api/route.js**:

“`js
export async function GET(req){
const {searchParams} = new URL(req.url);
const param = searchParams.get("/*Your param key here*/");
console.log(param)
}
“`

To get the request body:

“`js
export async function POST(req){
const body = await req.json()
console.log(body)
}
“`

Solution 3: Read Request Body and Query Params in Next 13’s API with App Router

To read the request body and query parameters in Next 13’s API with App Router, define a route in the `/pages/api/[…nextapirouter].ts` file and use the `req` parameter in the request handler function.

For example, to handle a GET request to `/api/example`, create a file at `/pages/api/example.ts` with the following code:

import type { NextApiRequest, NextApiResponse } from "next"

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  // Access query parameters
  const { name } = req.query
  
  // Access request body
  const body = req.body

  res.status(200).json({
    name: name,
    body: body,
  })
}

In this code, `req.query` contains the query parameters (e.g., `/api/example?name=John`), and `req.body` contains the request body (if applicable).

Solution 4: Read Request Body and Query Params in API Route.ts File Using NextURL

To read the request body and query parameters in a Next.js API route.ts file using the app router, follow these steps:

  1. Read Request Body:
    export const GET = async (req) => {
        const requestBody = await request.json();
    }
    
  2. Read Query Params:
    export const GET = async (req) => {
        const searchParams = req.nextUrl.searchParams;
        const foo = searchParams.get('foo');
    }
    

    The `req.nextUrl.searchParams` property provides access to URL query parameters as a URLSearchParams object. You can use the `get()` method to retrieve specific parameter values.

Video Explanation:

The following video, titled "Next.js 13 Crash Course | App Directory, React Server Components ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

... Next.js Crash Course: https://www.youtube.com/watch?v=mTz0GXj8NN0 Blog Post: https://www.traversymedia.com/blog/next-js-13 ... params Prop 37:07 ...