User logout when browser is closed but leave logged in when tab is closed (like old PHP apps)


When I want the behaviour that the user is logged out, when the browser closes or crashes, this was quite easy in PHP. But in meteor I searched a long time for a way to do this.

  • First thing I tried is to do some connection.onClose Magic but I have no loginToken assigned anymore when this function is called.
  • second try was to use some onunload. but that logs me out even when I reload the page or close another tab.
  • my final Idea was to simulate exactly what happens in PHP:

In PHP, I can do a


which sets the lifetime of the cookie to Session Only an so the cookie is present until the browser closes. As I want to have the functionality Toggelable in the user profile, I am also using a localstorage.setItem() to store if the user wants this behaviour.

some helpers:

window.setCookie = function (name,value,sec) {
    if (sec) {
        var date = new Date();
        var expires = "; expires="+date.toGMTString();
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";

window.getCookie = function(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();

the solution:

if localStorage.getItem("logoutOnResume") == "true"
	unless getCookie("resume")
		console.log "Logging out User on Resume"

window.localStorage.setItem("logoutOnResume", true)

Logout User When Window Closes
How to logout the user when he closes the browser or PC crashes

We will start a little blog about the stuff we find out according to meteor:


Thanks @kellertobi for posting this. nicely done!



Im just new in meteor. And I am not quite sure where to place the code above. In my understanding it would be on the login. But I am thinking that the if statement should be run whenever user navigates to any page in the application


run the code on client sided startup.


@kellertobi is it possible to create a meteor package or perhaps an npm package for this? just a thought =)

thanks for sharing