cannot set headers after they are sent to the client nodejs

Use the following code to prevent the "Cannot set headers after they are sent to the client" error in Node.js:

let headersSent = false;

app.use((req, res, next) => {
  if (!headersSent) {
    headersSent = true;
    next();
  } else {
    // Handle the error, for example:
    console.error('Headers already sent');
  }
});

This code uses a flag to check if headers have been sent before attempting to send them again. If the headers have already been sent, it logs an error message.