Fixing "[err_http_headers_sent]: Cannot Set Headers" Error in JavaScript | Step-by-Step Guide

When you happen to stumble upon the "Cannot set headers after they are sent to the client" error message, it's usually because you're trying to send multiple responses in a Node.js or Express app. It typically happens when you try to modify the response headers after you've already sent a response or multiple responses are being triggered by a single request.

To solve the "Cannot set headers after they are sent to the client" error, you'll need to ensure you're sending only one response and any modifications to response headers are done before sending them.

How to find cause of the "Cannot set headers after they are sent to the client" error

Below are a few steps you can take to troubleshoot the issue:

To showcase how the "Cannot set headers after they are sent to the client" error might happen, we've provided a piece of code that's wrongly approaching the issue and a correct one. Let's dig it!

const express = require('express');
const app = express();

app.get('/example', (req, res) => {
  // Simulating an asynchronous operation
  setTimeout(() => {
    res.send('First response'); // Sending the initial response

// Trying to send another response after a delay
    setTimeout(() => {
      res.send('Second response'); // Error: Cannot set headers after they are sent to the client
    }, 1000);
  }, 1000);
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

In the above code, when a GET request is made to the /example route, the server responds with "First response".

However, after a delay of 1 second, it attempts to send another response with "Second response". This will result in the "Cannot set headers after they are sent to the client" error because the server has already sent a response to the client.

To fix this issue, you need to make sure that you're sending only one response. Here's an updated version of the code that resolves the error:

const express = require('express');
const app = express();

app.get('/example', (req, res) => {
  // Simulating an asynchronous operation
  setTimeout(() => {
    res.write('First response'); // Using res.write() instead of res.send()

// Trying to send another response after a delay
    setTimeout(() => {
      res.end('Second response'); // Sending the second response
    }, 1000);
  }, 1000);
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

In this updated code, res.write() is used instead of res.send() to send the first response. Then, res.end() is used to send the second response. By using res.end(), you explicitly end the response and prevent any further modifications to the headers.

Once you make the above changes, you can ensure that only one response is sent to the client and resolve the error.