Search code examples
angulartypescriptpromisesupabase

Navigate to a URL when auth completed succesfully


I am currently developing a project for learning purposes, using Angular16 and Supabase as the backend. I have succesfully managed to sign in users with Github, Google and email (technically it does not matter how I sign in since the problem is the same with every provider).

My problem is the following, I provide the code and then explain:

login.component.ts:

async signInWithGithub(): Promise<void> {
    try {
      this.loading = true;
      this.supabase.signInWithGithub()
      .then(() => {
        this.router.navigate(['login']);
      })
      .catch((error) => {
        if (error instanceof Error) {
          alert(error.message);
        }
      })
      .finally(() => {
        this.loading = false;
      });
    } catch (error) {
      if (error instanceof Error) {
        alert(error.message);
      }
    } finally {
      this.loading = false;
    }
  }

This code should perform the navigation once the authentication has been successfully completed. What happens, however, is that the method performs the navigation first, and some time later, the authentication is completed and returns to the login component.

So my question is: How can I perform the navigation once authentication is complete?

I provide every single code I made myself, since supabase does almost everything for us.

supabase.service.ts:

signInWithGithub(): Promise<OAuthResponse>{
    return this.supabase.auth.signInWithOAuth({ provider: 'github' });
  }

The main method signInWithOauth() also return a Promise<OAuthResponse>

EDIT When I sign in with github (or any provider) it adds some queryparams to the URL and then the page refreshes.


Solution

  • Since signing in with a third party requires redirecting to their website for authentication you cannot handle the redirect using Angular code. The .signInWithOAuth method takes a options property which contains a redirectTo property that should be used to redirect you back to a particular page on your web app.

    this.supabase.auth.signInWithOAuth({ 
      provider: 'github', 
      options: { 
        redirectTo: 'http://example.com/login' 
      } 
    })
    

    Do note that the redirectTo take a full URL. Here is the docs.