TypeError: Response body object should not be disturbed or locked when using Next.js with Express

I’m encountering an error while using Next.js with a custom Express server. The error message is:

TypeError: Response body object should not be disturbed or locked

This occurs during API requests when I send a body with a POST request. The requests without a body (GET, even POST without sending a body, etc.) work fine.

I’m using a custom server with Express and have added middleware to allow Next.js to handle routing. The pages are served correctly, but the issue arises with the API route handler.

Here is the relevant part of my server setup:

import express from 'express';
import dotenv from 'dotenv';
import next from 'next';
import path from 'path';

dotenv.config({
    path: path.resolve(__dirname, '../.env'),
});

const PORT = Number(process.env.PORT) || 3000;

const app = express();
const nextApp = next({
    dev: process.env.NODE_ENV !== 'production',
    port: PORT,
    hostname: 'http://localhost',
});

const nextHandler = nextApp.getRequestHandler();

async function start() {
    await nextApp.prepare();
    app.use(express.json()); // Ensure the body parser is included
    app.use((req, res) => nextHandler(req, res));

    app.listen(PORT, () => {
        console.log(`Server started, and running at http://localhost:${PORT}`);
    });
}

start();

What I’ve Tried

  • Adding express.json() middleware: I included app.use(express.json()); to parse incoming JSON requests.
  • Ensuring proper order of middleware: I’ve made sure that the body parser is set up before the Next.js handler.
  • Checking for conflicting middlewares: I verified that no other middleware is interfering with the request handling.

Question

What could be causing this TypeError when sending a body with POST requests? How can I resolve this issue to ensure that my API routes work correctly with body data?

My version of next is 14.2.5 and my version of express is 4.18.2

Thank you for your assistance!