next.jsnext.js13

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


Did not found any solution here: https://nextjs.org/docs/app/api-reference/file-conventions/route.


Solution

  • In NextJS 13, with route.ts File Conventions in app dir, we can read query params and request's body with 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,
      });
    
    }