Is there a reliable way to log a user out when the browser is closed?

There is no reliable way to do this immediately when the client closes the browser. There's the beforeunload event, but even then, when you fire an ajax request during this event, it's not guaranteed to ever reach the server. Still then, you've a problem with multiple browser tabs.

Most reliable way is to have a relatively short session timeout in the server side (e.g. 1 minute) and introduce an ajaxbased heartbeat on the client side (e.g. every 30 seconds) to keep the session alive.

There may be better ways depending on the sole functional requirement for which you thought that this is the solution. For example, if your actual intent is to restrict all logins to 1 per registered user, then you'd better collect all logins and the associated sessions and then compare this on each login and invalidate the earlier session if any present. This way it'll work as well on clients with JS disabled.


If you aren't using cookies to preserve your users' login information, it should log them out when they close the browser, because any session cookies should be killed when the browser closes.

Obviously this isn't always the case (see here for an example of Firefox preserving login information after logging out) because "session restore" features we now blur the line between what is considered a "single browser session". (Personally, I think this should be classified as a bug, but that is only my opinion).

There are two possible techniques. The first would be (as yojimbo87 mentions before me) to use web sockets to keep a connection between client and server, and when the socket closes, kill the session. The issue here is that web sockets support is limited, and certainly not possible on anything other than bleeding edge browsers (FF4, Chrome, IE9, etc).

An alternative could be to use AJAX to constantly poll the server to tell it that the page is still being viewed, so if, for example, you send a keep-alive request via AJAX every 30 seconds, you'd store the timestamp of the request in the session. If the user then comes back to the page and the time difference between the current request and the last request is more than say... 45 seconds (accounting for latency), you'd know that the user closed their browser and need to log in again.

In both of these situations, there is however a fatal flaw, and that is that they rely on JavaScript. If the user doesn't have JavaScript enabled, you'd end up ruining the user experience with constant login prompts, which is obviously a bad idea.

In my opinion, I think its reasonable to simply rely on session cookies being deleted by the browser when the user closes the browser window, because that is what they are supposed to do. You as a developer can't be blamed when the client browser performs undesirable behaviour, since its entirely out of your hands, and there's no functional workaround.