Search code examples
firebaseangularfire2

Using Firebase signInWithRedirect can I configure it to redirect me back to a specific page


When I call

this.afAuth.auth.signInWithRedirect(provider) .then((credential) => { }) .catch((error) => this.handleError(error));

The redirect works correctly and is handled by firebase returning me to the login page. However it takes a while for the promise to complete

this.afAuth.auth.getRedirectResult().then((result) => { //Login or move to request additional info });

As the page has completely refreshed, I have no info that lets me know the page should not be showing login buttons, but instead should be showing a loading state.

Has anyone found a nice way to resolve this and hold the loading state, my initial attempt was to use angular routing to pass through a loading state, but annoyingly the signInWithRedirect service doesn't seem to change the url it redirects to.


Solution

  • FirebaseUI uses local storage to maintain whether to show the loading state or not (source). You should be able to do the same. However, if you don't want to handle local storage and don't mind polluting the URL, you can always add a unique query/hash param to URL before calling signInWithRedirect (Firebase Auth serializes the current URL and passes it as redirect_uri to the OAuth endpoint (source).

    Example using hash param

    // you can use any string here; just make sure to use the same one after reload
    window.location.hash = "redirecting"
    this.afAuth.auth.signInWithRedirect(provider)
      .then((credential) => {
      })
      .catch((error) => this.handleError(error));
    

    Then you can just check right after your component is rendered (after redirect):

    this.loading = (window.location.hash === "redirecting")
    // Clear the hash
    window.location.hash = ""
    

    Hope this helps.

    Edit

    You can also achieve setting the redirect URL to whatever you want by using window.history.replaceState and window.history.pushState to change the URL right before redirecting (similar to hash example above).