Can't set headers after they are sent to the client

The “[ERR_HTTP_HEADERS_SENT]:  Can't set headers after they are sent to the client” occurs when an express.js application tries to send multiple responses for a single request. To solve the error, make sure the following things:

  1. Don't send two responses for a single request.
  2. Don't use res.setHeader() after sending a response.
  3. Don't call next after response has been returned from the function body.

Don't send two responses for a single request

Always be careful to send only one response for a single request from the node server. The commonly used functions that send responses are res.redirect(), res.render(), res.send() and res.json(). 

The common scenario the issue arises when you have multiple conditional checks and send responses inside it. If you have any error in conditional logic, then there is a chance to send multiple responses. 

app.get('/', function(req, res){
    const message = "Hello world!";
    if(message != ""){
        res.send(message);
    }
    // Here throws an error: Can't set headers after they are sent to the client
    res.send("No message");
})

In the above code, there is an error in conditional logic which lead to calling the res.send() function twice. This causes the server to throw an error. To solve this issue, you can use return statement in each and every response send function as given below.

app.get('/', function(req, res){
    const message = "Hello world!";
    if(message != ""){
        return res.send(message);
    }
    return res.send("No message");
})

This solution is applicable to all response functions including redirect(). render(), send() and json().

Don't use res.setHeader() after sending a response

Make sure you are not using res.setHeader() after sending a response to the client. The res.setHeader() function can only be used before res.redirect(), res.render(), res.send(), res.json() and res.writeHead() functions.

The res.setHeader() sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, then its value will be replaced by a new given value. 

You are only allowed to call res.setHeader(name, value) until you call res.writeHead(statusCode). After writeHead() function, the headers are ready for send response. So you can only call res.write(data), and finally res.end(data) after that. If you are calling res.setHeader() after res.writeHead() will throw an error.

Don't call next after a response has been returned from the function body

When you are working on middleware in express, and if the current middleware function does not end the request-response cycle, you must need to call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

You should make sure that you are not calling next function after a response has been returned from the function body.

The below middleware function throws an error.

const checkSuperUser = function(req, res, next) {
    if (!req.user.isSuperUser) {
        res.redirect('/'); //ERROR OCCURS HERE
    }
    next();
};

To solve the error in above code use return statement in res.redirect('/').

const checkSuperUser = function(req, res, next) {
    if (!req.user.isSuperUser) {
        return res.redirect('/');
    }
    next();
};

How check headers are sent or not

You can check res.headersSent to determine whether the header are sent or not. If it is set to true, then the headers have already been sent. You can prevent multiple headers by checking this property of the response.

app.get('/', function(req, res){
    res.send('Hello World!');
    if(res.headersSent !== true) {
        res.send('Hello World!');
    }
});

Conclusion

To solve the error “[ERR_HTTP_HEADERS_SENT]:  Can't set headers after they are sent to the client”, always make sure you are only sending single response for a single request. Also ensure you are not using res.setHeader() or next() in middlewares after sending a response to the client.

Related Blogs

pm2 cluster

Scaling Node.js Applications With PM2 Clusters

Learn cluster modules in node js, install and configure PM2 in production, and implement PM2 clusters using the PM2 ecosystem without any modification in the current application code.

call-stack-in-javascript

What is Call Stack in JavaScript

JavaScript Call Stack is a mechanism to keep track of multiple function calls and manage execution context. This article describes how the call stack works with examples.

Factory Design Pattern in JavaScript

Factory Design Pattern in JavaScript

Factory allows you to handle all the object creation in a centralized location which helps the code clean, concise, and maintainable. Understand deeply with examples.

event loop and callback queue

Event Loop and Callback Queue in JavaScript

The event loop keeps monitoring the call stack and callback queue for executing callback functions. Read more about web APIs, callback queue, microtask queue, event loops, and starvation.

Cannot read property of undefined in JavaScript

Cannot read property of undefined in JavaScript

The TypeError: Cannot read property of undefined occurs when we try to read a property on an undefined variable or when we try to access a property on a DOM element that doesn't exist.

Greatest Common Divisor (GCD) in JavaScript

Find greatest common divisor (GCD) in JavaScript

Find the Greatest Common Divisor(GCD) of two numbers using the Euclidean algorithm in javascript. Calculate GCD for a given integer array.

How to Fix error:0308010C:digital envelope routines::unsupported

How to Fix error:0308010C:digital envelope routines::unsupported

To fix the error:0308010C:digital envelope routines::unsupported, enable the legacy provider for Node.js by passing --openssl-legacy-provider flag to webpack.

Javascript

What are Parameters, Arguments and Arguments Object in JavaScript

In JavaScript, the terms parameters, arguments, and arguments object are related to functions. Explains what they are with examples.

ckeditor

How to Integrate Custom Build CKEditor5 with React

Explains how to create a custom build CKEditor5 and integrate with react with sample code.