🍿 7 min. read

Creating New Supabase Users In NextJS

Monica Powell

This article walks through how to create new users for a Supabase database with an API written in NextJS. Note: at the time of this writing that Supabase is free for beta users which is pretty nifty as they include a hosted Postgres database which makes it faster to get an application up and running with a functional database. After the Beta period wraps up Supabase is planning on charging for hosting and will offer current Beta users 1 year of base tier usage for free.

I am currently building a SaaS (Software as a Service) website along with some other Egghead folks who are creating different types of SaaS applications. I am building this app from "scratch" and am currently in the phase of setting up authentication. For this project I am focused on learning new technology and documenting my learnings therefore I decided to try out Supabase, which is an Open Source alternative to Google's Firebase. The specific application I am working towards building is, Shine Docs which will allow folks to document professional achievements in a granular way.

Here's a blurb from the project's README:

[...]your place to shine, showcase and document more granular professional (or otherwise) achievements. Did you fix a gnarly production bug in record time? Did you give your 1st (or 20th) conference talk? Did you write out some solid documentation? Make sure you capture all of this awesomeness in more in a dedicated space. These types of receipts translate well into future resumes, negotiations, annual reviews and reminders to yourself. Inspired by Julia Evan’s article on getting your work recognized with a brag document.

This application is intended for folks looking for more structure with how they document granular professional achievements as well as those looking to have their achievements be more visible.

Set Up NextJS

If you do not yet have a NextJS site you should set up a boilerplate NextJS site as a starting point. This can be done by running the command npx create-next-app to spinup up a default NextJS site. After going through the prompts you should open your newly created directory containing the site.

The next step in setting up NextJS to interact with Supabase is to install Supabase dependencies with @supabase/supabase-js and then run yarn dev to run the site locally. If everything worked out you should be able to visit localhost:3000 and see your Next site running.

Set up Supabase Project

On Supabase we will create a new project and then retrieve the API key and URL from https://app.supabase.io/project/yourprojecturl]/settings/api which can be navigated to by going to your project > settings > API.

a screenshot of the Supabase settings page

In order for our application to be able to interact with our project's DB we will use environment variables to store the necessary values. As a Mac user, I tend to store environment variables in ~/.bash_profile.

You can add the following your ~/.bash_profile or wherever you store local environment variables:

1export SUPABASE_KEY="SUPABASEKEYFROMSETTINGSSCREEN"
2export SUPABASE_URL="SUPABASEURLFROMSETTINGSSCREEN"

If you already have a terminal session running then after you save your environment variables you should run source ~/.bash_profile to ensure that the newly exported environment variables are available to your NextJS app to access.

We will then create a supabaseClient.js file (in utils/) to set up the Supabase client that is used to interact with Supabase DB to use the URL and API key that were set in the previous step.

1import { createClient } from "@supabase/supabase-js"
2
3// retrieving environment variables
4const supabaseUrl = process.env.SUPABASE_URL
5const supabaseKey = process.env.SUPABASE_KEY
6
7export const supabase = createClient(supabaseUrl, supabaseKey)

Having the Supabase client live in a standalone file will be helpful when we have multiple API endpoints that interact with Supabase that require the same credentials.

Registering Supabase User

Now we will call Supabase to register users by creating a new API function inside of pages/api that uses our Supabase client.

1import { supabase } from "../../utils/supabaseClient"
2
3export default async function registerUser(req, res) {
4 // destructure the e-mail and password received in the request body.
5 const { email, password } = req.body
6
7 //make a SignUp attempt to Supabase and
8 // capture the user (on success) and/or error.
9
10 let { user, error } = await supabase.auth.signUp({
11 email: email,
12 password: password,
13 })
14 // Send a 400 response if something went wrong
15 if (error) return res.status(401).json({ error: error.message })
16 // Send 200 success if there were no errors!
17 // and also return a copy of the object we received from Supabase
18 return res.status(200).json({ user: user })
19}

You can learn more about HTTP status codes on what different status codes mean on my site https://www.httriri.com/.

Now, let's actually use the Supabase endpoint to create users. Our site's visitors will fill out a form to register therefore let's create a form that requires an e-mail and password and calls the previously created Register endpoint upon form submission. This form will then be imported and used in our index file, index.js.

1<form onSubmit={registerUser}>
2 <label htmlFor="email">Email</label>
3 <input
4 id="email"
5 name="email"
6 type="email"
7 autoComplete="email"
8 required
9 />
10 <label htmlFor="password">Password</label>
11
12 <input
13 type="password"
14 id="password"
15 name="password"
16 required
17 />
18 <button type="submit">Register</button>
19</form>

Now let's define what happens onSubmit when registerUser is called by defining registerUser. This function will receive the email and password typed into the form from the form submission event and will make a post request to the register endpoint.

1export default function Form() {
2 const registerUser = async event => {
3 event.preventDefault() // prevents page from redirecting on form submissiomn
4
5 // call default function in pages/api/register
6 // send the email and password from form submission event to that endpoint
7 const res = await fetch("/api/register", {
8 body: JSON.stringify({
9 email: event.target.email.value,
10 password: event.target.password.value,
11 }),
12 headers: {
13 "Content-Type": "application/json",
14 },
15 method: "POST",
16 })
17
18 const result = await res.json()
19 }
20
21 return (
22 <form onSubmit={registerUser}>
23 // above form omitted for brevity
24 </form>
25 )
26}

Now let's look at the response that we are getting back from the API request to the register endpoint.If we destructure res.json() like const { user } = await res.json() then we can see the user object for a successful request looks something like

1user {
2 id: '2de33395-b88b-4004',
3 aud: 'authenticated',
4 role: 'authenticated',
5 email: '[email protected]',
6 confirmation_sent_at: '2021-03-09T12:35:02.895833829Z',
7 app_metadata: { provider: 'email' },
8 user_metadata: {},
9 created_at: '2021-03-09T12:08:46.611304Z',
10 updated_at: '2021-03-09T12:35:03.466491Z'
11}

If we've received a 200 response (no errors!) and a user object back from our SignUp call to Supabase then we can redirect users to a message prompting them to confirm their e-mail address. We can use the NextJS router to handle this redirect:

1import { useRouter } from "next/router"
2
3export default function Form() {
4 const router = useRouter()
5 const registerUser = async event => {
6 event.preventDefault()
7
8 const res = await fetch("/api/register", {
9 body: JSON.stringify({
10 email: event.target.email.value,
11 password: event.target.password.value,
12 }),
13 headers: {
14 "Content-Type": "application/json",
15 },
16 method: "POST",
17 })
18
19 const { user } = await res.json()
20 if (user) router.push(`/welcome?email${user.email}`)
21 }
22
23 return <form onSubmit={registerUser}>{/*omitted for brevity*/}</form>
24}

Now we are currently redirecting folks to a Welcome page that doesn't exist so let's create a new page page/welcome.js.

1import Footer from "../components/footer";
2import { useRouter } from "next/router";
3
4export default function Welcome() {
5 const router = useRouter();
6 const { email } = router.query;
7return (
8 <main>
9 <p>
10 Thank you for signing up. Please check your {email} inbox to verify
11 your e-mail address!
12 </p>
13 </main>
14 <Footer />
15
16 </div>
17
18);
19}

If all went well then if you fill out the form with an email address and password then you should be redirected to the welcome screen, receive a confirmation e-mail from Supabase to the e-mail you submitted and see under the Authentication section of your project at https://app.supabase.io/project/[yourprojecturl]/auth/users that there is a new user in your users table with the email address that you just submitted. By default Supabase is set up to not allow users to log in until they verify their e-mail address, so unless you've changed that setting you should see the column Last Sign In showing the value "Waiting for verification...".

Example Code on GitHub

Checkout out the example code for this article at: https://github.com/M0nica/register-supabase-users-nextjs-example

That's all I have for now! But I am looking forward to sharing more about how I implement Supabase as I continue my app development.

This article was published on March 09, 2021.


Don't be a stranger! 👋🏾

Thanks for reading "Creating New Supabase Users In NextJS". Join my mailing list to be the first to receive my newest web development content, my thoughts on the web and learn about exclusive opportunities.

     

    I won’t send you spam. Unsubscribe at any time.

    Webmentions

    6
    • Jon Meyers
    • Nouha C
    • Joe Bell 🔔
    • Brian Rinaldi
    • Supabase
    • ᴮᴱDynamite⁷
    • Courtney Wilburn
    • Dazz (✷‿✷)
    • alex christie
    • Toni Mas
    • Aman Mittal ⚛️☕🖖 loves @Expo
    • iron ⎊ heart
    • Kurt Kemple
    • Ro
    • Paul Copplestone
    • Ant Wilson