Error: Can’t render headers after they are sent to the client [nodejs]

error can't render headers after they are sent to the client

The “Error: Can’t render headers after they are sent to the client” is a very common error in Node.js. This error is caused by the fact that Node.js buffers the response headers and body separately. So, if you try to set the headers after the body has been sent, you will get this error.

How to reproduce the error

There are many ways to reproduce this error. The most common way is to try to set the headers after the body has been sent. For example, let’s say you have the following code:

var express = require('express'); 
var app = express(); 
app.get('/', function(req, res) { 
    res.send('Hello World!'); 
    res.setHeader('Content-Type', 'text/plain'); 
}); 
app.listen(3000);

If you try to access this URL, you will get the following error:

Error: Can't render headers after they are sent to the client

How to fix the error

The most common way to fix this error is to simply move the code that sets the headers to before the code that sends the body. For example, the code above can be fixed like this:

var express = require('express'); 
var app = express(); 
app.get('/', function(req, res) { 
    res.setHeader('Content-Type', 'text/plain'); 
    res.send('Hello World!'); 
}); 
app.listen(3000);

In this case, the headers will be set before the body is sent, and the error will be fixed.

      Error: Can’t render headers after they are sent to the client ♥♥

Click here to Tweet this

Live Demo

If live demo fails to load properly on the website then please use the below button to open it in separate tab.

1. Reproducing Error

Please check the node console and you will see the error.

Open Live Demo

2. Solution

Open Live Demo