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:

<cfset this.name="findparishiltonsdignitysite">

You can quickly rename it like so:

<cfset this.name="findparishiltonsdignitysite2">

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.

Archived Comments

Comment 1 by todd sharp posted on 11/29/2007 at 7:46 PM

How do you feel about using a dynamic application name during development (like a UUID)?

Comment 2 by Raymond Camden posted on 11/29/2007 at 7:51 PM

I don't like it. Not sure why - but I just prefer my url hook method I guess. Also, while I like to restart the App scope on every hit (during dev), I'll normally use a second CFIF for session scope - that way it doesn't restart every hit, just when I want it to. (I should have said that above too.)

Comment 3 by shag posted on 11/29/2007 at 9:43 PM

i would add additional conditions to include server name and validated user id. this prevents accidental resets or even deliberate attempts from other users. you can also make sure it only occurs in dev/test environements vs prod.

Comment 4 by Kevin Sargent posted on 11/30/2007 at 3:45 AM

Dynamic application name during development leaves TONS and TONS (every page hit...) of orphaned application 'scopes' out there waiting to time out...