Supabase Authentication with React and Next js

How to authenticate a user with supabase!

Chris Wallace
2 min readFeb 5, 2021

So lately I’ve been supa 😉😉 into building apps with next js and supabase. So I decided to write up how I used supabase.io’s authentication to secure my next js app. After glancing through their documentation and numerous google searches, I was struggling to find an example on how to use Supabase Auth with user name /password. So I figured this would be a good excuse for me to write a simple Medium article that might help someone else.

Step 1: First let’s install supabase into your package.json

npm install @supabase/supabase-js

Than create a file called `supabase.js` to initialize the client and export it for the rest of your app

Step 2: Somewhere in your registration page after signing up a new user with ‘supabase.auth.signup’ we want to save the user object that is returned. To do this let’s create a separate public ‘user’ table and create a new record with the ID from the previous request and the rest of the fields from the signup form like first name, last name, etc.

Step 3: Next let’s create a react context / provider to listen to auth changes using the ‘supabase.auth.onAuthStateChange’ listener . This will help us know when the user has been created in supabase successfully and we will then use that reference to set the user object and pass it to all our pages / components.

Step 4: Let’s import our authentication provider we created in the previous step and wrap our main application in it so all our pages / components can subscribe to auth updates.

Step 4: Last let’s add a function to our login page so that returning users can login to their accounts

Conclusion

My Name is chris . I am a Software Engineer at modern health and if you enjoyed this article, please give it some claps and share it!

--

--

Chris Wallace

· Coder, Part-Time Ninja, Teacher, Sensai @cwallywall @Matchco #ReactJs