Recently I came across an issue with setting the HTML Header in my ColdFusion code. I simply tried to add such a header:
<cfheader name="csrf-token" value="value-of-my-csrf-token">
To my surprise, instead of the document being displayed properly, I got the following error:
Failed to add HTML header. ColdFusion was unable to add the header you specified to the output stream. This is probably because you have already used a cfflush tag in your template or buffered output is turned off.
I was aware that this error occurs if you want to set the header value after executing
<cfflush> is sending the part of the page that is already generated to the browser. Once it is sent, you are not allowed to set headers, because the connection is already open and headers sent.
What I was not aware of, is the fact that there are other conditions that trigger the data to be sent to the browser. The page I was working on is rather big. It consists of a large table with a lot of data in it. What I found was that the data is sent once the page size reaches 1MB of size. The ColdFusion engine is no longer holding the whole page in memory. The data are simply sent to the browser and – guess what – you are not able to set your headers afterward. Try to run such code on your server:
<cfoutput> We are trying to fill the data buffer with the data. #RepeatString("1234567890", 105000)# </cfoutput> <cfheader name="my-test-header" value="my-test-value"> <cfoutput> This text will not be visible. </cfoutput>
Most likely you will receive an error mentioned above.
There are at least three possibilities of dealing with such an issue.
- Instead of generating all your data directly on the page, save it to the variable first (for example using
<cfsavecontent>) and output it to the page after the
- Move the
<cfheader>statement to the top (or as high as possible) of your document.
- Set the Maximum Output Buffer size value in the ColdFusion admin. By default, it is set to 1024 KB which causes my data to be flushed at 1MB of size.
The choice is yours – it is not always the best to set the Maximum Output Buffer size to the high value, sometimes it is better to change the location of your