DEV Community

Cover image for How I build Register and Login page using Supabase
Suraj Vishwakarma
Suraj Vishwakarma

Posted on • Originally published at surajondev.com

How I build Register and Login page using Supabase

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 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 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 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

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 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

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.

    npx create-next-app@latest --experimental-app
Enter fullscreen mode Exit fullscreen mode

Note: To use the above command and further commands, you need to have nodejs 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:

    import AuthUI from "./Auth";
    export default function Register() {
      return (
        <div>
          <AuthUI />
        </div>
      );
    }
Enter fullscreen mode Exit fullscreen mode

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.

    npm i @supabase/supabase-js @supabase/auth-ui-react
Enter fullscreen mode Exit fullscreen mode

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.

    "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
    ); 
Enter fullscreen mode Exit fullscreen mode

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

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>
Enter fullscreen mode Exit fullscreen mode

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.

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

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.

    supabase.auth.onAuthStateChange((event) => {
       if (event == "SIGNED_IN") {
         router.push("/dashboard");
       }
    });
Enter fullscreen mode Exit fullscreen mode

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:

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

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

    "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;
Enter fullscreen mode Exit fullscreen mode

Testing the Application

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

    npm run dev
Enter fullscreen mode Exit fullscreen mode

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

Screenshot - Sign in page

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

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() 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 by Supubase. I hope the article has helped you understand in building a login/register page using Supabase. Thanks for reading the blog post.

Oldest comments (11)

Collapse
 
surajondev profile image
Suraj Vishwakarma

Which cool feature of Supabase do you use frequently?

Collapse
 
jonathanwilke profile image
Jonathan Wilke

I am basically using every feature of Supabase from Auth over Functions to Storage. Just love how simple it is to get everything set up and have Supabase manage the backend (and also its scaling) for you!

Really excited for what's coming in Supabase Launch Week 6!

Collapse
 
surajondev profile image
Suraj Vishwakarma

I recently started using the Database along with Authentication. I totally agree on how easy and simple is to set up supabase for your project.

Collapse
 
itskarim profile image
Karim

Great article 👏 , but you forgot to pass dependency array for useEffect.

Collapse
 
surajondev profile image
Suraj Vishwakarma

Need not to pass any dependent array as we need to run the function in useEffect only when the page loaded.

Collapse
 
itskarim profile image
Karim

But that will cause the function on each render, while passing the dependency array will make it run once in component's lifetime, No?

Thread Thread
 
surajondev profile image
Suraj Vishwakarma

Yep, useEffect runs on every re-render. But since we are not changing state, It won't render again and again. If you want, you can pass a state that looks for changes in the session or AuthState.

Collapse
 
jonathanwilke profile image
Jonathan Wilke

This is a great tutorial Suraj! Would love to see more Supabase content!

For everyone who is looking into using Supabase Auth, you should also check out supastarter.dev to get started faster and save a ton of time! It's a boilerplate that already integrates the functionality shown in this awesome article!

Collapse
 
surajondev profile image
Suraj Vishwakarma

Thanks, Jonathan. Supastarter looks nice tool! I have seen its growth recently through your Twitter account and Congrats on that🥳

Collapse
 
gamerseo profile image
Gamerseo

A really great project

Collapse
 
surajondev profile image
Suraj Vishwakarma

Thanks 🙏