Code With Wolf


How To Use React and Supabase Part 1: Setting Up a Project and Supabase Authentication

How To Use React and Supabase Pt 1: Setting Up a Project and Supabase Authentication

This demo will teach you how to connect a React application with Supabase and use Supabase's very easy authentication feature.

If you already know how to do this and want to jump into working more with a database using Supabase read the next part of this series, here.

What is Supabase and Why Use it?

Have you ever wanted to build an application very quickly? Maybe it's for a client or maybe it's to get it in front of potential customers or investors.

The issue is that building applications quickly, (or rapid protoyping) can be incredibly difficult because of the amount of architecture usually needed. You need a UI, DB, API, and maybe more components.

Supabase is a backend as a service (BaaS), but has a generous free tier and predictable pricing. (Areas where competitors like Firebase or Back4App fall short).

If you want to rapid prototype an minimum viable product (MVP) to get in front of potential consumers or investors, I have found no better tool than using the UI framework of your choice(React, Angular, Vue, etc) and Firebase. (Click here for an overview of how to choose a front end framework) and Supabase.

Supabase is built on PostgreSQL and essentially acts as your SQL DB and real-time API. Real-time features like chat apps are a breeze with Supabase.

For this demo, we will create a react project that uses Supabase. This will be the first part of a series that goes through some of Supabase's most important features.

The next part of the series is here.


Create The React Project


This tutorial assumes you have an understanding of JavaScript and at least a minimal understanding of react.

cd into a directory of your choice and run: npx create-react-app supabase-react.

(supabase-react is the name of the project. You can name your project anything you want).

Once the project is created you will see the typical default files for an app created with create-react-app. You can start the project.

cd supabase-react
yarn start

This should open a browser tab at localhost:3000 with a default react app running.


Install Supabase


Next, we will install the supabase js client.

yarn add @supabase/supabase-js


Create a Supabase Project


Next we need to create a Supabase project.

If you don't have an account, you can sign up for free here. Everything we do in this demo (at the time of publishing this post) will be within the confines of the free tier.

Once you have an account created, log in and create a Supabase project. You will need to give it a name (I called mine supabase-poc) and make sure to give it a strong password. I use LastPass to create strong passwords.

Now, when you select your Supabase project you will have access to an annon public key.


Connecting React With Supabase


Create a new directory in the src directory of the react project and name it supabase. In that directory, create a file index.js.

In the src/supabase/index.js, you will need to create the supabase client.

Use the below code, except replace the first parameter with the URL in your supabase project's settings. And the second parameter should be the project's public annon key.

import { createClient } from '@supabase/supabase-js'

export default createClient('https://project.supabase.co', 
'<YOUR PUBLIC ANNON KEY>')

Setup Supabase Authentication with GitHub

One of my favorite features of Supabase is how simple it is to set up authentication.

Head over to your supabase project and navigate to the Auth page.

So far, there are no auth providers set up. On the left side nav bar, select Settings.

When you scroll down to the External Auth Providers section, you will see a long list of 3rd party auth providers you may use.

For this demo, we will only use Github. (Although each provider will be very similar to set up).

Toggle on Github.

Create An OAuth App In Github

The next step is to create an OAuth app in github. To do this, navigate to GitHub.

Go to your settings and select Developer Settings, and then OAuth Apps.

Next, click the button to add a new OAuth app.

Fill out the form. You'll need a homepage URL. I used http://localhost:3000 for now. And for your Auth Callback add https://<YOUR_PROJECT_REFERENCE>.supabase.co/auth/v1/callback.

After that, a Client ID and Client Secret are created for you in Github. Copy and paste them into the Supabase Authentication Console where you previously enabled Github auth. (They recently started adding default values in there so just replace those with the values generated in Github).

Click the 'Save' button in the auth settings.

Sign In User Interface

Now we are ready for a UI to log in with Github.

In /src/App.js, replace the current code with this:

 user, session, error } = await supabase.auth.signIn({
      provider: 'github'
    });
  }
  
  async function signout() {
    const { error } = await supabase.auth.signOut();
  }

  return (
    <div className="App">
    <button onClick={signInWithGithub} >Sign In With Github</button>
    </div>
  );
}

export default App;

You'll now see a button and if you click on it, it will allow you to login with Github and then redirect you back to localhost.

Next, we will complete the login process.

How to Use Supabase Authentication with React

One of the more confusing parts about using OAuth with Supabase and React is what to do after you are redirected back to localhost.

That is what this blog post is about, and where other posts and the Supabase docs seem to fall short.

Currently, our App.js is just a button that does part of the login work for us. Now, we will make a few simple change to complete the entire login process.

Our src/App.js now should look like this:

import "./App.css";
import supabase from "./supabase";
import { useState } from "react";

function App() {
  const [user, setUser] = useState(null);

  supabase.auth.onAuthStateChange((event, session) => {
    if (session?.user) {
      setUser((u) => (u = session.user));
    }
  });

  async function signInWithGithub() {
    const {
      user,
      session,
      error,
    } = await supabase.auth.signIn({
      provider: "github",
    });
  }

  async function signOut() {
    const { error } = await supabase.auth.signOut();
    setUser((u) => (u = null));
  }

  return (
    <div className="App">
      {!user ? (
        <button onClick={signInWithGithub}>Sign In With Github</button>
      ) : (
        <button onClick={signOut}>Log Out, {user?.email}</button>
      )}
    </div>
  );
}

export default App;

Looking at this code, this will handle just about all of the auth workflow that we need.

We are able to sign in with the signInWithGithub() function and sign out with signOut(). One import piece is the listener for AuthStateChanges, which is what the code in the supabase.auth.onAuthStateChanges() block handles. This will constantly listen for any changes (including if a user already has an active session when first entering our web app so they don't need to log in unnecessarily).

You might be wondering what happens to a user that hasn't visited our web app before and doesn't yet have an account. Since we are not managing our own authentication, they can create an account in our application by creating an account in Github and we will have them handle our auth.





© 2022 Code With Wolf