How to tell if a header has been set in ColdFusion

Here is an interesting question - how do you determine if something has been added to the response header? I needed to know this because of an bug in ColdFire where cflocation stopped working when ColdFire was used. Turns out that when you use cflocation, the debug template is still executed. I'm not sure why the template still runs - but when my code set information in the header, it apparently broke the data that cflocation had also set in the header. So obviously I needed to see if a cflocation header existed - and if so - suppress ColdFire. Easy, right?

Turns out it isn't that simple. ColdFusion provides a way to get request headers (getHTTPRequestData), but there is no built in way to get response headers. Luckily this is something built into the plumbing down in Java, and ColdFusion provides us a way to get there with getPageContext(). Consider the following code block:

<cfheader name="foo" value="1">

<cfset response = getPageContext().getResponse()>
<cfif response.containsHeader("foo")>
<cfif response.containsHeader("foo2")>

I set a header named foo. This is the header I'll be testing for. I then grab the page context object and from that grab the response object. How did I know to do this? I just looked around the Java API docs a bit. That is where I discovered that the response object has a "containsHeader" method that does exactly what it sounds like - returns true or false if the response contains a particular header.

If you find you need this functionality, try this simple UDF I wrote. (Which will be up on CFLib later today.)

function responseHeaderExists(header) {
	return getPageContext().getResponse().containsHeader(header);
Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA