How I build Register and Login page using Supabase
Tags: webdev, react, javascript, beginners
Published: 2022-12-06 11:30:00

# Introduction

One of the challenging things to build in an application is Authentication. It is a process of identifying the user. We do that by registering the user and then letting them login into the account. For this, we need to create the Register and Login page in our front-end application. We need to add a login method with Email or any OAuth provider. We also need to store user data in a database. For secure login, we need to send a token (can be a JWT token for web application). This a quite a work to do in an application and the process is repetitive for every application. That’s why we have Supbabase to help us in managing Authentication.

[Supabase](https://supabase.com/) is an open-source Firebase alternative. It provides support such as a Postgres database, Authentication, instant APIs, Edge Functions, Realtime subscriptions, and Storage. It has been my go-to tool for Authentication since I first used it. It supports Email, Phone, and 17 major third-party OAuth providers. It has a free tier that is best for building individual projects. 

[Auth UI](https://supabase.com/docs/guides/auth/auth-helpers/auth-ui) is a pre-build Authentication component from Supabase. It is for building the login/registering page. Today, we are going to use the Supabase and Auth UI to build a Register/Login page. We are going to look into the following topics:


- Adding a project to Supabase
- Using Auth UI to build the frontend component
- Email Provider for registering and login

[Supabase’s launch week](https://supabase.com/launch-week) will begin on the 12th of December. It will extend to the 16th of December. In this, they are going to launch new features every day. Grab your ticket and look out for some amazing features that are coming to the platform. I already got mine. 

![Supabase Launch Week Ticket](https://paper-attachments.dropboxusercontent.com/s_2594E255DCFE7FE59AAA2F62E121C6816FC5D73BEDA3A0965C4AC7D153A45D0C_1670297681915_launchweek-ticket-og.png)

Now, let’s get started with the project.

# Adding a project to Supabase

First, let’s set up our project on the supabase dashboard. Visit [supabase.com](https://supabase.com/) then click on `Start your project` from the right of the nav bar. This will take you to the sign-in page. Enter your details for sign-in or sign-up as you required. After logging in, you will be redirected to the project page. From here, click on `New project` to create a project. On Create new project page, you will be asked to enter details of your project.  

![Screenshot - Create a new project page](https://paper-attachments.dropboxusercontent.com/s_2594E255DCFE7FE59AAA2F62E121C6816FC5D73BEDA3A0965C4AC7D153A45D0C_1670168454105_image.png)


Fill in the details of your project. Enter the project’s name as per your choice. For passwords, you can use the `Generate a password` for generating password. Select the region that is nearest to the user of your project. In the free tier, you can create two projects. After filling the detail, click on `Create new project`. It will take a few minutes to set up the project.


# Frontend with Auth UI

You can use React or any other framework that is built upon React for building the component. I am going to use the NextJS 13. You can create a NextJS project with the below command. Run the command in the terminal.

```bat
    npx create-next-app@latest --experimental-app
```

> Note: To use the above command and further commands, you need to have [nodejs](https://nodejs.org/en/) pre-installed.

Create a folder with the name `register` inside the `app` directory. Inside it creates a `page.js` file. Here is the code for it: 

```jsx
    import AuthUI from "./Auth";
    export default function Register() {
      return (
        <div>
          <AuthUI />
        </div>
      );
    }
```

It is a layout page that will hold our AuthUI component. Let’s build the AuthUI component. Create a file with the name `Auth.js` inside the `register` directory.  

## Auth.js

To use Supabase’s Authentication and Auth UI, we need to install `@supabase/supabase-js` and `@supabase/auth-ui-react` respectively. Run the below command in the terminal to install the libraries. 

```bat
    npm i @supabase/supabase-js @supabase/auth-ui-react
```

> Note: Run the above command in the terminal from the root directory of the NextJS project.

Here is the code for the `Auth.js` in context with imports.

```jsx
    "use client";
    
    import { useEffect} from "react"; 
    import { createClient } from "@supabase/supabase-js"; // for supabase's function
    import { ThemeSupa, Auth } from "@supabase/auth-ui-react"; // for Auth UI
    import { useRouter } from "next/navigation";
    
    const supabase = createClient(
      process.env.NEXT_PUBLIC_SUPABASE_URL,
      process.env.NEXT_PUBLIC_ANON
    ); 
```

You can see the comments for the imports description. We have created a `supabase` variable for using the supabase client in our application. We have used the environment variable for storing sensitive data. Let’s create that too. We need two variables from our Supabase project that is Supabase URL and Anon. Visit your project’s dashboard on supabase. From there go to Project Setting and then API. 

![Screenshot - API Setting page](https://paper-attachments.dropboxusercontent.com/s_2594E255DCFE7FE59AAA2F62E121C6816FC5D73BEDA3A0965C4AC7D153A45D0C_1670172809796_image.png)


You will find your Project URL and Anon key there. Now create a `.env` file in the root of your project. Add the details of both as the environment variable. 

```
    NEXT_PUBLIC_SUPABASE_URL=<Project ULR>
    NEXT_PUBLIC_ANON=<anon public>
```

> Note: Prefix the environment variable’s name with NEXT_PUBLIC_. This will be directly loaded to the client.

Let’s move on and add a return to our `Auth.js` component. Here is the code for it.

```jsx
    return (
        <div className="auth">
          <Auth
            supabaseClient={supabase}
            appearance={{ theme: ThemeSupa }}
            theme="light"
            providers={["github", "twitter"]}
            view="sign_in"
          />
        </div>
      );
    };
```

The `Auth` component from the `@supabase/auth-ui-react` is for the login/register component. Let’s look into the used props:

- supabaseClient: It takes the supabase that we have declared in the beginning.

- appearance: It is where we pass the theme of the component. At present, they have two themes. We have used `ThemeSupa`. You can customize the appearance by overriding the styles. But for right now, we are going to use the default theme. 

- theme: There are two kinds of themes based on the color mode that is dark/light.

- provider: They are the third-party OAuth provider. We have listed the `github` and `twitter`. You need to enable it from the Authentication section for its working.

- view: It is the value for the page such as sign-in, sign-up, forget the password, or update the password. We have passed the default page as `sign-in`.

Once it is done. Now, it's time to add some more features to the application.

## Redirect after successful sign-in

After successful login/sign-up, we need to redirect the user to some other route. We can do that by listening to the Auth State. In supabase, there is a method for that. `onAuthStateChange` will listen to any auth change. We can perform tasks based on the event. 

```jsx
    supabase.auth.onAuthStateChange((event) => {
       if (event == "SIGNED_IN") {
         router.push("/dashboard");
       }
    });
```

In the above code, the router.push() will redirect the user to the `/dashboard` route. This will only happen if the event is “SIGNED_IN”.

## If the session is active then redirect the user to the dashboard 

When a user with an active session visits the route, it should redirect the user to the /`dashboard` route. We can use the `useEffect` hook to look for the session once the page is loaded. We can get the session details using `supbase.auth.getSession()` method. Here is the useEffect code:

```jsx
    useEffect(() => {
        const checkSession = async () => {
          const { data} = await supabase.auth.getSession();
          if (data.session) {
            router.push("/dashboard");
          }    
        };
        checkSession();
      });
```

Together with all the functionality, our `Auth.js` will look like this:

```jsx
    "use client";
    
    import { useEffect } from "react";
    import { createClient } from "@supabase/supabase-js";
    import { ThemeSupa, Auth } from "@supabase/auth-ui-react";
    import { useRouter } from "next/navigation";
    
    const supabase = createClient(
      process.env.NEXT_PUBLIC_SUPABASE_URL,
      process.env.NEXT_PUBLIC_ANON
    );
    
    const AuthUI = () => {
      const router = useRouter();
      useEffect(() => {
        const checkSession = async () => {
          const { data } = await supabase.auth.getSession();
          if (data.session) {
            router.push("/dashboard");
          }
        };
        checkSession();
      });
    
      supabase.auth.onAuthStateChange((event) => {
        if (event == "SIGNED_IN") {
          router.push("/dashboard");
        }
      });
    
      return (
        <div className="auth">
          <Auth
            supabaseClient={supabase}
            appearance={{ theme: ThemeSupa }}
            theme="light"
            providers={["github", "twitter"]}
            view="sign_in"
          />
        </div>
      );
    };
    
    export default AuthUI;
```

Testing the Application

Go to `localhost:3000/register` after running the NextJS server. You can run it by running the below command:

```bat
    npm run dev
```

On `/register` route, you will have the below output screen:

![Screenshot - Sign in page](https://paper-attachments.dropboxusercontent.com/s_2594E255DCFE7FE59AAA2F62E121C6816FC5D73BEDA3A0965C4AC7D153A45D0C_1670223190979_image.png)


You will need to first create an account. You can do that by clicking `Don``'``t have an account? Sign up` link. Enter details regarding registering.

![Screenshot - Sign up page](https://paper-attachments.dropboxusercontent.com/s_2594E255DCFE7FE59AAA2F62E121C6816FC5D73BEDA3A0965C4AC7D153A45D0C_1670223227396_image.png)


After entering the details, click on `Sign up`. If everything goes well, you will be redirected to `/dashboard` route. 


> Note: We haven’t created any dashboard route. Make sure you create a route with components. 

# Additional Features

There are many authentication features that I haven’t implemented. You can work on the project to add those. A few of them can be:

- Creating `dashboard` route
- Using [getSession()](https://supabase.com/docs/reference/javascript/auth-getsession) from supabase to verify the active session of the user for `/dashboard` route. 
- Add more features as per your requirement

# Conclusion

From the article, you can think of How amazing Supabase is! We have a proper authentication system with Supbase UI and Authentication. The authentication is via Email provider. It was quite easy to build it with supabase’s method. You can try the platform for features other than Authentication such as Database, Edge Functions, Realtime subscription, or Storage.

Make sure to look out for the upcoming [launch week](https://supabase.com/launch-week) by Supubase. I hope the article has helped you understand in building a login/register page using Supabase. Thanks for reading the blog post.