Sling Academy
Home/Node.js/Fixing ERR_HTTP_HEADERS_SENT in Node.js and Express

Fixing ERR_HTTP_HEADERS_SENT in Node.js and Express

Last updated: December 28, 2023

The ERR_HTTP_HEADERS_SENT error occurs in Node.js and Express applications when an attempt is made to modify the HTTP headers of a response after they have already been sent to the client. This can happen if you’re trying to send a response to the client but the response has already been transmitted, or if a response is being sent multiple times.

Reasons Behind the Error

  • Multiple Responses: Sending more than one response to a client request.
  • Async Operations: Attempting to set headers after an asynchronous operation has completed and a previous response has already been sent.

Steps to Fix the Error

  1. Be sure to only send one response per request.
  2. Use return statements to prevent further code execution after sending a response.
  3. Check your route handlers for any unintended multiple response calls.
  4. Ensure you handle errors properly so that they don’t lead to additional responses being sent.

Complete Code Example

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

app.get('/', (req, res) => {
  // Imagine some logic here that may result in sending a response
  res.send('First response');

  // More logic here that attempts to send another response by mistake
  // This will cause ERR_HTTP_HEADERS_SENT
  // res.send('Second response'); // Comment this out to prevent the error
});

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

Additional Solutions

If your code involves asynchronous operations (like database queries), be sure to handle the response only once. For example:

app.get('/user', (req, res) => {
  User.findById(req.params.id, (err, user) => {
    if (err) {
      // Handle the error and send a response
      return res.status(500).send(err);
    }
    if (user) {
      // Send user data as a response
      res.send(user);
    } else {
      // Handle case when user isn't found
      res.status(404).send('User not found');
    }
    // No further response should be sent here!
  });
});

Every response method (like res.send, res.json, res.end) should be called once per request. Using return with these methods can help prevent further execution which might cause additional response attempts.

Next Article: How to Get a URL Parameter in Express

Previous Article: How to Render HTML Views in Express.js

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates