How to create a session timeout warning for your web application using jQuery

Warn your users before their authorized session expires

Credit: ThinkStock

If you've got a web application or SaaS project which requires a user to be logged in, chances are their login will expire at some point. Using sessions is one of the most popular methods of authenticating users, whether it be forms authentication in ASP.NET and Java or $_SESSION based in PHP. If a user leaves their browser logged in on your app for an extended period of time, then returns to perform additional actions they may end up losing the changes they've made when they submit back to the server due to an expired session. This is particularly prevalent in medical software as HIPAA regulations require a maximum 20 minute session expiration. Needless to say users can get very frustrated when this occurs without warning.


['Rogue clouds' giving IT staffs nightmares and 7 must-have project management skills for IT pros]

Most web applications using session based authentication provide a sliding expiration for the session, meaning every time the user performs an action, the expiration timer is reset. If you know the session expiration length, for example 20 minutes, you can use this jQuery script to provide your users with a warning prompt when their session is about to expire.


To customize the script for your own application, edit the 3 variables at the top of the script to suit your needs. Then, update the function calls in the methods, sessPingServer() and sessLogOut() to call real functions in your application. Then call the initSessionMonitor() method from your jQuery onLoad method.

The result of this script is that a javascript confirmation box will pop up on the user's screen when your warning minutes variable has been exceeded. If the user presses OK before the session expiration is exceeded, the server will be pinged to refresh the session expiration. If the user presses cancel or does not press OK within the expiration limit, the user will be logged out of the system.

This script relies on jQuery so be sure it's loaded before this script. The source can be downloaded here:

ITWorld DealPost: The best in tech deals and discounts.
Shop Tech Products at Amazon