Tuesday, October 9th, 2007

Managing sessions in an Ajax-enabled application

Category: Ajax

A recent post by Raymond Camden caught my attention as it focused on how to properly manage a web application’s server-side sessions when using Ajax to make server requests. In the post, the application in question uses a dashboard paradigm and has no page refreshes:

Imagine you have an Ajax-based site. The front end acts like a dashboard. In other words, the user never leaves the page, but executes various actions that do Ajaxy-type things on the back end. But if the user sits by and does nothing, how can I recognize a session timeout when the next Ajax-based call is done?

One solution thrown out was to create a ping service but as your audience grows, that’s going to send a lot of extra HTTP requests to the server. Dan Switzer offered another option as well using HTTP response headers.

So how would Ajaxian readers handle this situation?

Link to the post: How can you timeout a session in an Ajax-based application?

Posted by Rey Bango at 8:58 am

3.4 rating from 37 votes


Comments feed TrackBack URI

I’ve not read it yet, but as far as I’m concerned this is a simple task.
If you have your sessions set to timeout after 15 minutes, simple loop a polling script every 16 minutes to check the session state. If session has timed-out then kill the main page.

Comment by stuart — October 9, 2007

After reading the above to suggestions…..
The problem with waiting for the next ajax call is that any secure info which is left on the main screen can still be viewed. A auto-logout version is, in my opinion, the most secure way.
Imagine you have logged in to something like a bank account, and for some reason you need to leave the room, anyone can come in and read the screen. With a auto-logout – the info is only ever available for up to 16 minutes (or whatever you set) of inactivity.

Comment by stuart — October 9, 2007

@ stuart, I was just thinking the same thing, I think the question can be answered a number of ways depending on what the system wants.

Do you want:

– Session kept alive without needing user interaction (ping at intervel)
– Session killed after a certain amount of time of inaction
– Session about to be killed with a countdown popup warning thing after a certain amount of time of inaction (my personal fave)
– Session natural timeout and how to handle with your next XHR after that.

Comment by JP — October 9, 2007

I once built a site with a digg-spy-like widget. I had a couple of monitoring functions/timeouts that had to do with user activity.
One monitor would keep track of user activity (mouse movement, typing, scrolling, etc..). If the user would stop interacting with the page, I would increasingly slow down the refresh rate. Normally I would pull every ten seconds for the first minute of inactivity, then I would increment by 1.5X for the next minute. 2x for the third, 4x and so on to eventually be almost stopped until the user would do something and the whole process would be reset.

This function made sure that the server would work hard only for active users and not those gone MIA.

The above function would also start a second monitor/timeout of 15 minutes from the end of the first minute of inactivity. After 15 minutes I would prompt the user to do something within 30 seconds or I would log them out.

I initially also had the monitoring system notify the server of the inactivity of the user through appending a parameter to all ajax calls. So if before I would call the widget.php?sessid=1234 now I would call widget.php?sessid=1234&active=0

This was useful only for the IM module.

But pretty much what Stuart said would work. It all depends if the session info are deemed important or contain private info.

Comment by Diego Scataglini — October 9, 2007

The problem with polling every XX seconds method doesn’t actually mean that a session has expired.

If the user has multiple tabs open on the same site, just because one page hasn’t been looked at in XX seconds, doesn’t mean the session isn’t still alive.

Also, in the application I’m currently working on, only a single login can be active at the same time (to prevent multiple users from using the same login credentials at the same time.)

This means that a session can expire “prematurely”.

This is why it’s import to make sure that AJAX calls have some way of reporting a session has expired.

That doesn’t mean you can’t use a XX second poll to do something to the UI, but it shouldn’t be your primary method of session checking.

Comment by Dan G. Switzer, II — October 9, 2007

JP is right, the first thing is to decide what is the desired behavior – which of course will be different for different sites. If this isn’t done, it’s too easy to cook up a good solution to the wrong problem. (I’m as guilty of that as anyone…)

Comment by Michael Geary — October 9, 2007

We do a ping to the server each minute to keep session alive (and to check various stuff). If that for some reason fails we handle session logout like this (prototype example):


if a user is not logged in the page returns a http 403 – forbidden status.


var url = “/getSomeData/”;
var opt = {
method: “post”,
onSuccess: success,
// Handle 404
on404: function(t) {
alert(‘Error 404: location “‘ + t.statusText + ‘” was not found.’);
// Handle other errors
onFailure: function(t) {
if ( t.status == 403 ) {
doLogin(); // show login box to user
asynchronous: false

new Ajax.Request(url, opt);

(code not tested..just example :)

Espen Antonsen
System Developer

Comment by Sleepyhead — October 9, 2007

A typical non-ajax enabled secure site doesn’t log you out automatically if you leave your browser open just sitting there. If you try and do anything after your session has expired then its handled accordingly. I don’t see why an ajax-enhanced website would need to handle the situation much differently, unless thats a requirement, that a page left alone for longer than the session timeout gets cleared of its data its presenting to the user. Otherwise, it seems to me you’d just handle their logout/redirect if they tried to send a new request (xhr or http) after session is timed out. Like stated already, it probably just comes down to the requirements and security level needed.

Comment by Brad Harris — October 9, 2007

It depends what kind of non-ajax secure site you’re talking about.
All trading, bank (bank of america), credit card (american express, mbna) and even some City Library (browardlibrary.org) website, that I go to, log you out after 3-15 minutes of inactivity. So in my esperience, yes they do log you out.

Comment by Diego Scataglini — October 9, 2007

Just put a meta tag refresh set to your session time out. When it kicks off, it takes you to the login screen.

Comment by Phill Kenoyer — October 9, 2007


That does not work because when you make requests, the session timeout is reset. Since you are deaing with an Ajax page, the meta refresh will not reset.

Something back from 2005: http://ajaxian.com/archives/update-users-session-with-ajax

Comment by Eric Pascarello — October 9, 2007

I don’t see the need for a server side session. One of the major advantages of Ajax is that we can now manage the state of the user session from within the browser. Combine that with one of the known best practices: Keep the server side stateless (This is one of my lessons learned from J2EE: Don’t use Statefull Session Beans unless you really, really need it). The advantage of the stateless server side is its scalability and availability due to the ease of load balancing.

The result is also a simple and easy to understand application architecture. There is a user session as long as the end-user has the browser window open with the Ajax application. Note that that’s exactly what end-users are familiar with using desktop applications.

I’ve now build two Ajax business applications following this application architecture and with more success than I hoped for. These Ajax applications are very stable (a short server restart won’t be noticed by the end-user), perform well and use minimal server side resources. Also application maintenance is easy because there is no complicated client-server state synchronization.

Keep it simple.

Comment by Arjen Wassink — October 9, 2007

I agree with Arjen, I have built several RIA Apps, and stateless requests are one of the best options you cake take. But almost all the applications will need some kind of server session (maybe only for security purposes) so you’ll always have to deal with session status check at the client side. The optimal solution I’ve found was the use of response headers to check the existence of the session.

Comment by Pablo Viojo — October 9, 2007


Comment by navot — October 10, 2007

Why time out?

Timeouts are bad for usability. Many people leave their computer running all the time — they expect to be able to walk away, then come back the next day and start working again. From their viewpoint, timeouts are obnoxious.

If your architecture doesn’t scale without timeouts, get a new architecture.

Can’t afford to? Can you afford to dump people’s sessions? Amazon.com keeps people’s shopping carts for weeks — they’d be throwing $$ away if they dumped people’s shopping carts because of the limitations of their software.

Comment by Paul Houle — October 10, 2007

If you use ‘sessions’ from a third party to handle authentication to your site, I’ve got some Kool Aid for you to drink.

This is how big sites handle user authentication:


this can be implemented in about 100 LOC…

Comment by Paul Houle — October 10, 2007

The “textHtmlHandler” of DWR could help in some cases: http://getahead.org/dwr/other/errors

Comment by ignatius — October 10, 2007

I agree with Paul. You should not dump people’s sessions because of limitation in your software.
Pablo, i agree with you that there will be a need for a security session. But in my opinion that’s more an infrastructure issue than an application issue. The AJAX business applications I mentioned rely on SSO (SPNEGO/Kerberos) between the browser and the web server. When the security session is lost at the server, SSO creates a new security session without the end-user even noticing.
SSO or not, the key is recreating the security session for the user-session. What’s wrong with the user having to reenter the log-on credentials when he/she was away for an hour? I won’t bother, as long as I can continue to work. It can even be an security requirement. My desktop locks when I don’t use it for 10 minutes.

Comment by Arjen Wassink — October 12, 2007

Leave a comment

You must be logged in to post a comment.