I ran across an issue which came up because of switching to html5mode in my Angular app and I thought I'd share.
- Not seen before with html5mode = false, was suddenly faced with an issue where onAuthStateChanged was being called every time you refresh the browser or manually input a URL.
- Didn't conform to how I anticipated how onAuthStateChanged would work - because nothing had CHANGED about the auth state. It was triggered on every external event. (Refresh or manual input of URL)
Desired use case:
- Remove hash in URLs by switching to html5mode(true)
- When refreshing page or inputting URL in browser, direct to the correct page
- At the same time, redirect users who log out to the home page
The above has worked fine with hashes and I've never seen this issue before switching to html5Mode(true).
The actual behaviour - and onAuthStateChanged events
- Refresh page or input URL in browser, and on all browsers other than Chrome desktop, the site redirects to the home page
- This happens because an onAuthStateChanged event is triggered when you refresh browser
The issue was happening because of how I was handling onAuthStateChanged conditions. The idea here was that if someone logs out, it should redirect them to home.
vm.auth.$onAuthStateChanged(function(firebaseUser) {
if (firebaseUser) {
vm.validUser = firebaseUser;
//console.log("Signed in as:", firebaseUser.uid);
} else {
// When refreshing browser in Firefox, Safari or mobile browsers this gets triggered. Does not get triggered on Chrome desktop.
console.log("Signed out");
$location.path('/'); // Redirects to home
}
});
onAuthStateChanged gets triggered on refresh.
Recommendations/Questions
- I wonder why I never saw this issue before I implemented html5? Is that just luck?
- Shouldn't the authorization status persist after browser refresh? Why does it persist on Google Chrome desktop but not the other browsers?
- If the authState hasn't actually changed, should this method be triggered? Could there be another method - "onAuthStateRefresh" or some such?
- Add note in documentation maybe to highlight this?
If nothing else, hopefully this is useful.
P.S. I also note Frank's comment on a similar issue here, which I wish I had found in the first hour rather than the 10th! :)