In recent years, there has been a growing trend towards serverless architecture and cloud-based applications. One popular database option for such applications is Supabase, an open-source platform that offers a suite of tools for building scalable and secure applications. In this article, we will explore how to use Supabase with Next.js, a popular React-based framework for building web applications.

Table of Contents:

  1. What is Supabase?
  2. Prerequisites
  3. Setting up Supabase-JS
  4. Authentication with Supabase
  5. CRUD Operations with Supabase

What is Supabase?

Supabase is an open-source alternative to Firebase, which provides backend services to build serverless applications. Supabase provides a suite of tools for building scalable and secure applications. It includes an open-source PostgreSQL database, authentication, and real-time subscriptions. It is built on top of Postgres and has a GraphQL-based API.

Prerequisites

Before we begin, you should have a basic understanding of Next.js and React. You should also have a Supabase account and a project set up.

Setting up Supabase-JS

We need to set up Supabase in our Next.js project. We can do this by installing the @supabase/supabase-js package using npm or yarn.

npm install @supabase/supabase-js

Once installed, we can initialize Supabase in our Next.js project by creating a supabase object with our Supabase project URL and API key. We can then use this object to interact with our database.

import { createClient } from "@supabase/supabase-js";

const supabaseUrl = "https://<your_supabase_url>.supabase.co";
const supabaseKey = "<your_supabase_api_key>";

export const supabase = createClient(supabaseUrl, supabaseKey);

Authentication with Supabase

Supabase provides various authentication methods, including email and password, Google, Facebook, GitHub, and more. For this example, we will be using email and password authentication. To use email and password authentication, we need to create a sign-up and login form in our Next.js application.

Creating a sign-up form

Next, let's create a sign-up form that allows users to create an account with their email and password.

import { useState } from 'react'
import { supabase } from '../lib/supabase'

function SignUpForm() {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')

  async function handleSignUp(event) {
    event.preventDefault()

    const { user, error } = await supabase.auth.signUp({
      email,
      password,
    })

    if (error) {
      console.error(error)
    } else {
      console.log(user)
    }
  }

  return (
    <form onSubmit={handleSignUp}>
      <input
        type="email"
        value={email}
        onChange={(event) => setEmail(event.target.value)}
      />
      <input
        type="password"
        value={password}
        onChange={(event) => setPassword(event.target.value)}
      />
      <button type="submit">Sign up</button>
    </form>
  )
}

In this example, we use the useState hook to manage the state of the email and password input fields. When the user submits the form, we call the supabase.auth.signUp method to create a new user with the specified email and password.

Creating a sign-in form

Now, let's create a sign-in form that allows users to sign in with their email and password.

import { useState } from 'react'
import { supabase } from '../lib/supabase'

function SignInForm() {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')

  async function handleSignIn(event) {
    event.preventDefault()

    const { user, error } = await supabase.auth.signIn({
      email,
      password,
    })

    if (error) {
      console.error(error)
    } else {
      console.log(user)
    }
  }

  return (
    <form onSubmit={handleSignIn}>
      <input
        type="email"
        value={email}
        onChange={(event) => setEmail(event.target.value)}
      />
      <input
        type="password"
        value={password}
        onChange={(event) => setPassword(event.target.value)}
      />
      <button type="submit">Sign in</button>
    </form>
  )
}

We define a handleSignIn function that calls the signIn method on supabase.auth with the email and password entered by the user. If there's an error, we log the error message. We use the useState hook to manage the email and password state, and we bind the input fields to their respective state using the value and onChange props. Finally, we render an input field for email, an input field for password, and a button to trigger the handleSignIn function when clicked.

This will return a user object containing the user's email and other information, which we can use to render personalized content for them.

CRUD Operations with Supabase

Once you have connected your Next.js app with Supabase, you can start performing CRUD (Create, Read, Update, Delete) operations with your database. Here's an example of how to perform these operations using Supabase's JavaScript client library in Next.js:

The first step is to set up a database in Supabase. Here's how you can do that:

  1. Log in to your Supabase account and click on the "SQL" option on the left side of the screen.
  2. Click the "New Table" button to create a new table. For this tutorial, we'll create a table named "todos" with the following columns:
  3. id (type: integer, constraint: primary key)
  4. title (type: text)
  5. completed (type: boolean)

Create Operation

To create a new record in your Supabase database, you can use the insert() method. Here's an example of how to create a new user record:

import { supabase } from '../lib/supabase'

const createUser = async (data) => {
  const { data: todo, error } = await supabase.from('todos').insert(data).single()
  if (error) throw new Error(error.message)
  return user
}

In this example, data is an object containing the data for the new user record. The insert() method is used to insert this data into the todos table in the database. The single() method is used to retrieve only the newly created record.

Read Operation

To retrieve records from your Supabase database, you can use the select() method. Here's an example of how to retrieve all todo records:

import { supabase } from '../lib/supabase'

const getUsers = async () => {
  const { data: todos, error } = await supabase.from('todos').select('*')
  if (error) throw new Error(error.message)
  return todos
}

In this example, the select() method is used to retrieve all records from the todos table in the database.

Update Operation

To update an existing record in your Supabase database, you can use the update() method. Here's an example of how to update a todo record:

import { supabase } from '../lib/supabase'

const updateUser = async (id, data) => {
  const { data: todo, error } = await supabase.from('todos').update(data).match({ id }).single()
  if (error) throw new Error(error.message)
  return todos
}

In this example, id is the ID of the todo record to be updated, and data is an object containing the updated data. The update() method is used to update the data in the todos table, and the match() method is used to specify which record to update.

Delete Operation

To delete a record from your Supabase database, you can use the delete() method. Here's an example of how to delete a user record:

import { supabase } from '../lib/supabase';

const deleteUser = async (id) => {
  const { data: todo, error } = await supabase.from('todos').delete().match({ id }).single()
  if (error) throw new Error(error.message)
  return todo
}

In this example, id is the ID of the todo record to be deleted. The delete() method is used to delete the record from the todos table, and the match() method is used to specify which record to delete.

With these examples, you should now have a good understanding of how to perform CRUD operations with Supabase in your Next.js app.

Conclusion

In conclusion, Supabase is a powerful and flexible tool for building modern web applications with Next.js. Its ease of use, strong security features, and support for real-time updates make it an excellent choice for developers looking to build robust and scalable applications. With Supabase and Next.js, you can quickly and easily build applications with complex database functionality, authentication, and authorization, without having to worry about the underlying infrastructure. So, if you're looking for a powerful, modern, and easy-to-use database solution for your Next.js applications, be sure to give Supabase a try.

Related posts

Tell us about your goals.

Every goal is a milestone waiting to be achieved. Share your vision with us, and let's turn aspirations into accomplishments together. We're all ears, ready to make your goals our mission.

Connect with Sales Team
Connect with HR Team
Connect with Partnership Team

Tell Us Where You Want To Be…

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.