ColdFusion wsPublish tag and destroyed session variable
January 9th 2018
325

We are back with a solution to another, perhaps not so widely known bug. This time it’s a ColdFusion native bug involving its own websocket and session variables. Frankly, it was bugging us (no pun intended)  for the past 2 years. Here’s the problem in detail:

We are running an application that utilises ColdFusion’s native websockets functionality. In a most basic scenario, we run a cfcomponent with several functions to create a notification record and insert it in the database. Then, as one would, push it via the webscoket so all the connected users with the relevant permissions receive it instantaneously. All is nice and well, right? NO.

What we have noticed, is that in most cases once the wsPublish tag is executed, the SESSION variable is completely wiped out. But only for that particular request. Consider the following steps:

  1. Create notification record and insert it in the database
  2. Form notification html structure with various ColdFusion variables, some of which could be based on the set session variables
  3. Push notification using wsPublish

These would work perfectly fine and you would never realise that something’s gone wrong. Even if your every function within the component(s) is wrapped in the cftry, it would still run smoothly with no exceptions thrown.

Now consider adding a 4th step - step that involves performing some further actions with session variables within the same request. Boom! You will receive an unceremonious message that reads word for word as the following: ’Variable SESSION is undefined.’ Not variable within the session, as that would ’definitely maybe’ point to some sloppy programming on the developer’s side. No, the entire SESSION variable is suddenly missing!

As it turns out, for whatever the reason, the wsPublish clears the whole request scope on completion which also involves the SESSION variable. That is just crazy. However, after much deliberation, debugging and soul searching we found a rather simple solution - wrap the entire notification pushing call into the cfthread tag and you are good to go. Yes it is that simple! Here’s an example of the complete call:

The ’publish_notification’ call is just a call to the named function that executes whatever it needs to execute using the wsPublish tag. That is it. Once the call is completed, wsPublish will clear the scope, but only of a separate thread we have just created. This way we are free to carry on error free and happily utilise the session variables as nothing has happened.

Hope this helps someone out in the time of need.

Back To Blog