Getting Started with Supabase: A Comprehensive Tutorial

This tutorial aims to provide software developers with a comprehensive guide on getting started with Supabase. Supabase is an open-source Firebase alternative that offers a suite of tools for building scalable and secure applications. In this tutorial, we will cover the basics of Supabase, including setting up an account, database management, authentication, real-time subscriptions, API endpoints, deployment, and more.

getting started supabase comprehensive tutorial

Introduction

What is Supabase?

Supabase is an open-source platform that combines the power of PostgreSQL and the simplicity of Firebase. It provides developers with a set of tools and services, including a database, authentication, real-time subscriptions, and API endpoints, to build scalable and secure applications.

Why use Supabase?

Supabase offers several advantages for software developers. Firstly, it leverages the power of PostgreSQL, a popular and robust relational database management system. This ensures data integrity, scalability, and flexibility for your applications. Secondly, Supabase provides a suite of services that are commonly required in modern applications, such as user authentication, real-time subscriptions, and API endpoints. This eliminates the need for integrating multiple third-party services and simplifies the development process. Lastly, Supabase is open-source and self-hostable, giving you complete control over your data and infrastructure.

Prerequisites

Before diving into Supabase, make sure you have the following prerequisites:

  • Basic knowledge of SQL and relational databases.
  • Familiarity with JavaScript and Node.js.
  • An active internet connection.

Setting Up Supabase

Creating an Account

To get started with Supabase, you first need to create an account. Visit the Supabase website and click on the "Get Started for Free" button. Fill in the required details, including your email address and a password, and click on the "Create Account" button. You will receive a confirmation email to verify your account.

Creating a Project

Once you have created an account, you can create a new project in Supabase. Log in to your Supabase account and click on the "New Project" button. Enter a name for your project and choose a region for hosting your database. Click on the "Create Project" button to create your project.

Configuring Supabase

After creating a project, you will be redirected to the project dashboard. Here, you can find your project URL, API URL, and API key. These credentials are required to connect to your Supabase database and make API requests. Make sure to securely store these credentials as they are sensitive.

To configure Supabase in your application, you need to install the Supabase client library. You can install it via npm by running the following command:

npm install @supabase/supabase-js

Once installed, you can initialize the Supabase client by providing your project URL and API key:

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

const supabaseUrl = 'https://your-project-url.supabase.co';
const supabaseKey = 'your-api-key';
const supabase = createClient(supabaseUrl, supabaseKey);

With the Supabase client initialized, you are now ready to manage your database.

Database Management

Creating Tables

To create a table in Supabase, you can use the supabase.createTable() method. This method takes two arguments: the table name and an object representing the table schema. The schema defines the columns and their data types for the table.

const { data, error } = await supabase.createTable('users', {
  id: {
    type: 'integer',
    primaryKey: true,
    notNull: true,
  },
  name: {
    type: 'text',
    notNull: true,
  },
  email: {
    type: 'text',
    notNull: true,
    unique: true,
  },
  createdAt: {
    type: 'timestamp',
    default: 'now()',
  },
});

In the above example, we create a table named "users" with four columns: "id", "name", "email", and "createdAt". The "id" column is defined as an integer primary key, while the "name" and "email" columns are defined as non-null text fields. The "createdAt" column is a timestamp with a default value of the current timestamp.

Defining Relationships

Supabase supports defining relationships between tables using foreign keys. To define a foreign key relationship, you can use the supabase.createTable() method and the references property in the column definition.

const { data, error } = await supabase.createTable('orders', {
  id: {
    type: 'integer',
    primaryKey: true,
    notNull: true,
  },
  userId: {
    type: 'integer',
    references: 'users',
  },
  totalAmount: {
    type: 'numeric',
    notNull: true,
  },
});

In the above example, we create a table named "orders" with three columns: "id", "userId", and "totalAmount". The "userId" column is defined as an integer and references the "users" table. This establishes a foreign key relationship between the "orders" and "users" tables.

Performing CRUD Operations

Supabase provides a set of methods for performing CRUD (Create, Read, Update, Delete) operations on your database. Here are some examples:

Create

To insert a new row into a table, you can use the supabase.insert() method.

const { data, error } = await supabase.from('users').insert([
  { name: 'John Doe', email: '[email protected]' },
  { name: 'Jane Smith', email: '[email protected]' },
]);

In the above example, we insert two new rows into the "users" table.

Read

To fetch data from a table, you can use the supabase.from() method.

const { data, error } = await supabase.from('users').select('*');

In the above example, we fetch all columns (*) from the "users" table.

Update

To update existing rows in a table, you can use the supabase.update() method.

const { data, error } = await supabase
  .from('users')
  .update({ name: 'John Smith' })
  .eq('id', 1);

In the above example, we update the "name" column of the row with the ID of 1 in the "users" table.

Delete

To delete rows from a table, you can use the supabase.delete() method.

const { data, error } = await supabase.from('users').delete().eq('id', 1);

In the above example, we delete the row with the ID of 1 from the "users" table.

Authentication

Setting Up Authentication

Supabase provides built-in authentication functionality to handle user registration, login, and session management. To enable authentication in your project, you need to configure the authentication providers and initialize the authentication client.

Configuring Providers

To configure authentication providers, navigate to the "Authentication" section in your project dashboard. Here, you can enable and configure various providers, such as email/password, Google, GitHub, and more. Follow the on-screen instructions for each provider to set up the required credentials.

Initializing the Authentication Client

To initialize the authentication client, you can use the supabase.auth object.

const auth = supabase.auth;

With the authentication client initialized, you can now perform various authentication actions.

User Registration

To allow users to register in your application, you can use the auth.signUp() method.

const { user, error } = await auth.signUp({
  email: '[email protected]',
  password: 'password123',
});

In the above example, we register a new user with the email "[email protected]" and the password "password123".

User Login

To authenticate users in your application, you can use the auth.signIn() method.

const { user, error } = await auth.signIn({
  email: '[email protected]',
  password: 'password123',
});

In the above example, we authenticate the user with the email "[email protected]" and the password "password123".

Real-time Subscriptions

Enabling Real-time Subscriptions

Supabase provides real-time subscription functionality, allowing you to listen for changes in your database and receive updates in real-time. To enable real-time subscriptions, you need to configure the triggers and initialize the real-time client.

Configuring Triggers

To configure triggers, navigate to the "Database" section in your project dashboard and select the table for which you want to enable real-time subscriptions. Click on the "Triggers" tab and create a new trigger. You can define the trigger condition and the action to be performed when the condition is met.

Initializing the Real-time Client

To initialize the real-time client, you can use the supabase.realtime object.

const realtime = supabase.realtime;

With the real-time client initialized, you can now listen for changes and handle real-time updates.

Listening for Changes

To listen for changes in a table, you can use the realtime.from() method.

const unsubscribe = realtime
  .from('users')
  .on('INSERT', (payload) => {
    console.log('New user inserted:', payload.new);
  })
  .subscribe();

In the above example, we listen for new rows (INSERT) in the "users" table. Whenever a new row is inserted, the callback function is invoked, and the new row data is logged to the console.

Handling Real-time Updates

To handle real-time updates, you can use the appropriate callback functions based on the type of change (INSERT, UPDATE, DELETE).

const unsubscribe = realtime
  .from('users')
  .on('*', (payload) => {
    console.log('Change occurred:', payload);
  })
  .subscribe();

In the above example, we listen for any change (*) in the "users" table. Whenever a change occurs, the callback function is invoked, and the change payload is logged to the console.

API Endpoints

Creating Custom API Endpoints

Supabase allows you to create custom API endpoints to perform server-side logic and interact with your database. To create a custom API endpoint, you can use the Supabase CLI or the Supabase Dashboard.

Supabase CLI

To create a custom API endpoint using the Supabase CLI, navigate to your project directory and run the following command:

supabase generate api my-endpoint

This will generate a new API endpoint in the api directory of your project. You can then implement your server-side logic in the generated files.

Supabase Dashboard

To create a custom API endpoint using the Supabase Dashboard, navigate to the "API" section in your project dashboard. Click on the "New Endpoint" button and enter a name for your endpoint. You can then define the route, HTTP methods, and serverless function code for your endpoint.

Securing API Endpoints

Supabase allows you to secure your API endpoints using various authentication mechanisms, such as API keys, JWT tokens, or custom authentication logic. To secure an API endpoint, you can use the supabase.auth.api() method.

const { data, error } = await supabase.auth.api('my-endpoint').get('/path');

In the above example, we secure the API endpoint named "my-endpoint" and make a GET request to the "/path" route.

Testing API Endpoints

To test your API endpoints, you can use tools like cURL or Postman. Make sure to include the appropriate authentication headers or tokens when making API requests to secured endpoints.

curl -H 'Authorization: Bearer <api-key>' https://api.supabase.co/my-endpoint/path

In the above example, we make a cURL request to the "/path" route of the "my-endpoint" API endpoint, including the API key in the Authorization header.

Deployment

Deploying Supabase

To deploy Supabase, you can use the Supabase CLI or the Supabase Dashboard.

Supabase CLI

To deploy Supabase using the Supabase CLI, navigate to your project directory and run the following command:

supabase deploy

This will deploy your Supabase project to the Supabase hosting infrastructure.

Supabase Dashboard

To deploy Supabase using the Supabase Dashboard, navigate to the "Hosting" section in your project dashboard. Click on the "Deploy" button to deploy your project to the Supabase hosting infrastructure.

Scaling Supabase

Supabase is designed to scale horizontally by adding more instances of the Supabase service. You can scale your Supabase project by upgrading your plan or contacting the Supabase team for custom scaling options.

Monitoring and Maintenance

Supabase provides monitoring and maintenance tools to help you keep your application running smoothly. You can monitor your project's performance, view logs, and perform maintenance tasks using the Supabase Dashboard.

Conclusion

In this tutorial, we covered the basics of getting started with Supabase. We learned how to set up a Supabase account, create a project, configure Supabase, manage the database, enable authentication, utilize real-time subscriptions, create custom API endpoints, deploy Supabase, and perform monitoring and maintenance tasks. With the knowledge gained from this tutorial, you are now equipped to build scalable and secure applications using Supabase. Explore the official Supabase documentation for more advanced features and capabilities. Happy coding!