Cannot set headers after they are sent to the client Cannot set headers after they are sent to the client

When you are using Node.js with Express and youíve received the dreaded error [err_http_headers_sent]: cannot set headers after they are sent to the client where do you even begin with err_http_headers_sent'. This article will explore common causes of this error, such as calling res.writeHead, res.write, or res.redirect.

A problem occurs when servers send out headers after the message has been received by the client. Node JS applications send multiple responses to the same request - eg. calling the request twice instead of a single request with one response res.send headers.


Table of contents:

  1. Why am I receiving the error message can't set headers after they are sent to the client Nodejs?
  2. Calling the request handler function res.writeHead too early
  3. Calling res.redirect then setting more data

  4. Calling next after response has been returned

  5. Check for duplicate function calls before an error occurs
  6. Understanding Node Error [ERR_HTTP_HEADERS_SENT]
  7. Check for problematic middleware
  8. How do you fix Cannot set headers after they are sent to the client?
  9. Uncovering the mystery

Why am I receiving the error message canít set headers after they are sent to the client Nodejs?

Below are the three most common reasons this error occurs when you are using Express as a web server with Node.js as the request handler function nodejs response.end:

  1. Calling res.writeHead too early
  2. Calling res.redirect then setting more data
  3. Calling next after response has been returned from the function body or the function caller
  4. Check for duplicate function calls

Keep reading for examples of how each of these three common reasons may occur with examples of what the incorrect code will look like and how it can be fixed so you donít continue to receive error [err_http_headers_sent]: cannot set headers after they are sent to the client. For all examples I will start with a generic Express function that looks as follows that will use the res object to return the response body using the following functions:

router.get('/',function (req,res,next){
});

This function will respond to the homepage of your website 'err_http_headers_sent'. Letís now go through the common scenarios causing Node.js and Express to throw error: canít set headers after they are sent.. Once you solve this problem, be sure to read more of my Node.js tutorials that are sure to help you improve your JavaScript and Node.js skills even more so you wonít ever receive the error message: canít set headers after they are sent!

Calling the request handler function res.writeHead too early

If in your Express route function, you can call res.setHeader as many times as you like and the middleware items writes code: 'err_http_headers_sent'. The second you call res.writeHead or res.write Express has permanently set headers for the response of your call. Any further calls to res.setHeader will error with cannot set headers after they are sent to the client nodejs. Here is an example of what to look for when you set headers that may have been accidentally called more than once from one request that can write two responses to the client:

router.get('/',function (req,res,next){
// Call to some middleware
// middleware code calls: res.writeHead();
res.setHeader('Content-Type', 'text/html');
// Exception thrown after setHeader call
});

If you have middleware or your own code that is writing the headers are the response, you will want to set your own headers before calling the offending code that could cause canít set headers after they are sent:

router.get('/',function (req,res,next){
res.setHeader('Content-Type', 'text/html');
// Call to some middleware
// middleware code calls: res.writeHead();
// Finish executing the request
});

Calling res.redirect then setting more data

After you call res.redirect Express has finalized the request. Any further setting of data prior to Express performing the redirect will also cause canít set headers after they are sent. Letís look at example that may cause this from the response header as the client error because there was more than one response in your callback functions:

router.post('/',function (req,res,next){
// Do something with the post data
// Redirect to thank you page
res.redirect('/thankyou');
// Additional function call that causes error
next();
});

In this example, a post request is made. The code does something with it then redirects the user to a thank you page. After this action a call to - in this example - next(); is made that causes the header error. After calling res.redirect(); be sure no other code is executed:

router.post('/',function (req,res,next){
// Do something with the post data
// Redirect to thank you page
res.redirect('/thankyou');
});

Calling next after response has been returned

The final common scenario that I know about is calling next after res.end has been called. This is once again common when middleware unbeknownst to you calls res.end.

router.get('/',function (req,res,next){
// Some middelware that executes
// res.end
// Additional function call that causes error
next();
});

To solve this, ensure the call to next happens before the call to res.end. Ideally the middleware either doesnít call res.end and your code will be responsible for ending the request OR the middleware calls next for you before it calls res.end. Hopefully one of these three tips will help you solve the dreaded Canít render headers after they are sent.

Check for duplicate function calls before an error occurs

Error: Could not add header when sending. errors usually occur after the response of several requests is sent. If the request was redirected once you checked, the following functions can be avoided by using this function: Below is the main response method that you should check with the set headers when an error occurs from the actual function.

Understanding Node Error [ERR_HTTP_HEADERS_SENT]

If youíre a Node JS developer thereís a runtime error that can cause: HTTP HEADER_SEND: Canít set ĎHeadersí after sending them to a user with common errors. It starts to be difficult to find the reason the code threw how the error happened from the response object.

This error can be very frustrating and you might get a slight variation of this error, so it might be anyone of the following that are all very similar but contain slight variations:

  • error [err_http_headers_sent]: cannot set headers after they are sent to the client
  • [err_http_headers_sent]
  • rror [err_http_headers_sent]: cannot set headers after they are sent to the client
  • cannot set headers after they are sent to the client http-server
  • error - error [err_http_headers_sent]: cannot set headers after they are sent to the client

Check for problematic middleware

In the app-use method, append objects to the Server.Prototype.Stack of the connect interface. Upon receipt of the requested request, the server moves the stack and calls the request response method. If an intermediate object sends a message in response body or headers without calling respond() and right after it calls respond(), an error is thrown.

How do you fix Cannot set headers after they are sent to the client?

The problem with the err-http_headers_send is solved by using a return statement. The error happens because you have a problem with status 400. JSON executes, and your process wonít go down.

Uncovering the mystery

Errors are triggered by a server sending multiple response messages to a customer. Typically. The server sends the client an initial response to the request, either a successful response for the request or an incorrect response and has now unexpectedly tried to send another response.

Published on Jun 1, 2022

Tags: Node js Tutorial | express

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.