next.jsapp-router

NextJS app router post request body parsing failing version 15.1.7


I am simply making a post request to my nextjs api and trying to read the body. The body is logging as undefined. I have set the header "Content-Type": "application/json". I am using NextApiRequest as the request 'type' and I have tried using the default Request as the type. Where is bodyParser configured and how can I confirm that it is enabled? Apparently it is enabled by default?

Front end:

const response = await fetch("api/my/api/na", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ tx: "longunimportantdata" }),
            });

Back end API:

import { NextApiRequest } from "next";

export async function POST(request: NextApiRequest) {
    try {
        const { tx } = request.body
        console.log(tx)        
        }

        return new Response(JSON.stringify(({ txId })));
    } catch (error: any) {
        console.error("Transaction error:", error);
        return new Response(JSON.stringify(({ "error": error.message })), { status: 500 });
    }

}

Solution

  • Please change URL to await fetch("/api/my/api/na" (added leading slash), and use

    import {NextRequest} from "next/server"
    
    export async function POST(request: NextRequest) {
        const body = await request.json()
       // remaining code here