Skip to content

Instantly share code, notes, and snippets.

@melignus
Last active April 12, 2022 14:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save melignus/d3302e7aa4ec97b9ab0d to your computer and use it in GitHub Desktop.
Save melignus/d3302e7aa4ec97b9ab0d to your computer and use it in GitHub Desktop.
Simple session timeout check for client side applications.
// Non-jquery example from http://stackoverflow.com/questions/333634/http-head-request-in-javascript-ajax
/**
* The idea here is to poll against a route that requires authentication,
* in this case /session_health_check, on an interval.
* The important part is the header in the response. Because
* the current session goes with the request, polling against the endpoint
* can either trigger a refresh on the page which should initiate the auth
* flow, or you can popup a dialogue that says that you need to
* re-authenticate with a ?next= to send the use back to the page.
*
* There are hundreds of ways I've seen this implemented and this is just one
* quick and dirty way of managing client sessions. You could put the status
* check on the ajax calls for updates to client side view model, you can set
* an initial time against your .Net timeout settings to warn a user their
* session is about to expire and refresh with calls to clear the interval,
* have numerous ways of telling the user or simply refresh the page and rely
* on the application authentication flow to take care of the rest.
*/
function sessionCheck( callback )
{
var http = new XMLHttpRequest();
http.open('HEAD', '/session_health_check');
http.onreadystatechange = function() {
if (this.readyState == this.DONE) {
if (this.status != 200) {
callback();
}
}
};
// Set a timeout for if the server doesn't respond at all
http.timeout = 10000; // Or whatever is an appropriate response time from the server
http.ontimeout = function() {
callback(); // or do stuff
};
http.send();
}
/**
* Inside your init, setup a timeout to check on whatever interval
* you feel is appropriate. reAuthFunction is where you start your flow,
* anything from a popup to a window.location.reload()
*/
setInterval( function() { sessionCheck(reAuthFunction) }, 3000 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment