Search code examples
jsonnext.jspostmanmime-typesdouble-quotes

Next.js API Route mysteriously modifying JSON payload


For some reason, when I send JSON formatted data through Postman as raw text, I have no issues. When I send the exact same data through Postman as raw JSON (the difference should only be that the content-type header is application/json instead of application/text), I end up with my double quotes stripped and my strings switched to single quotes.

Original payload example (Postman sends this):

{ "id": "blahblahbloo", "time": "hammer" }

Unintended transformation (NextJS receives this):

{ id: 'blahblahbloo', time: 'hammer' }

To be clear, I get the exact same thing (which is what I expect) when I send as raw text via Postman:

// Postman sends this and NextJs receives this when set to raw text    
{ "id": "blahblahbloo", "time": "hammer" }

I'm not explicitly doing anything to read the content-type and transform the data. My endpoints with this issue is a NextJS Dynamic Route: https://nextjs.org/docs/api-routes/dynamic-api-routes


Solution

  • Next.js API routes have a built-in bodyParser middleware that will parse the incoming request's body based on its Content-Type header.

    From the API Middlewares documentation (emphasis is mine):

    API routes provide built in middlewares which parse the incoming request (req). Those middlewares are:

    • req.cookies - An object containing the cookies sent by the request. Defaults to {}
    • req.query - An object containing the query string. Defaults to {}
    • req.body - An object containing the body parsed by content-type, or null if no body was sent

    Sending the payload as application/json will have the API route convert the req.body to a JavaScript object, hence striping the double-quotes.


    While the bodyParser middleware is automatically enabled by default, you can disable it if you want to consume the body yourself.

    // In the API route
    export const config = {
        api: {
            bodyParser: false
        }
    }