Ask a Jedi: When does a session start?

Darren asks:

I want to use on sessionstart to initiate a session variable and then use that value in a function call to to set the default language for a site but I get an error saying the session var isn't there. Does the session start after the first request? Should I use on application start instead?

No and no. onSessionStart will definitely fire before onRequestStart. Turns out - Darren had another problem. He had written his Application.cfc without the session variables in his onSessionStart, he had hit his site, and then he had modified the onSessionStart. Since his session had already started, the method didn't run again.

There are a few ways to get around this. One simple way is to quickly rename your Application. If you had:


You can quickly rename it like so:


This is kind of hacky, but it will truly force ColdFusion to restart the application next time you hit it.

Another option, and what I typically use, is a URL hack:

<cfif structKeyExists(url,"reset")> <cfset onSessionStart()> </cfif>

This will not be single threaded, but during development, you typically don't care about it. I use this same hook to rerun onApplicationStart as well. In fact, during development I'll typically always run the code by appending OR 1 to the end.

Of course, the Nuclear Option is to restart ColdFusion, but even with ColdFusion 8 being super fast, that's overkill.

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