clouddatabasereal-time

Supabase - Intro to the Open Source Firebase Alternative

Aftab Alam

Aftab AlamMarch 15, 2021

10 min read–––

Aftab Alam

While recently shopping for ways to persist the view counts for the articles on this site I stumbled upon Supabase. I was all-in to leverage Firebase for the scenario, but Supabase felt very less overwhelming to start with, and I couldn't give it a miss. This write-up dives into the details of what it is and how it can be useful to the Javascript apps near you.

What is Supabase?

Any moderately complex application that needs to support a near real-time and distributed multi-user model(Slack, Google Docs, Excel), requires a persistence layer — with the ability to keep client applications in sync. Maintaining a on-premise solution for the same is not a very desirable thing in many cases, so we outsource the job to cloud-based DB hosts(AWS Redshift, Amazon Aurora, etc) and build real-time functionality atop it. But, even with a cloud-managed, multi-geographic, global-scale DB it could be too much of work to write and maintain all of the supporting system with a real-time data synching capabilities. If you're a business, depending on your use case, it may not be a good strategic move to invest your time and money in building the supporting real-time architecture unless you're building the next Slack or MS Teams.

So what should you do instead? Won't it be good if your persistence-layer cloud provider can also have real-time sync abilities baked in?

It's 2021, and you won't have too look very much and far to find a solution that fits your bill for any application type you imagine to build. For a scenario like this too, there are applications that can not just manage the persistence layer for you but also have all the bells and whistles to make CRUD operations and update propagation convenient through purpose-built SDKs.

Supabase is one of such tools that you can use today to store data and synchronize it effortlessly across various connected clients(Web & Mobile apps)

Why Supabase?

A blog touching upon the whats and whys of Supabase woudn't be complete without touching a bit on Firebase. Firebase found in 2011, and later acquired by Google in 2014, was the first web product I came across that set out to achieve the aforementioned goals. Powered by a NoSQL store BTS, it’s able to support persistence while giving you ways to establish a long-living connection with the persistence store(powered by Web Socket) to observe and act on changes in a near real-time fashion. On top of it, it offers modules that complement the core system with an authentication layer(email & social logins), Storage(for files), and Firebase functions so that you could model your apps around a Serverless pattern to perform various one-off functions. It's like a one-stop-shop for all your app needs, that you could get up and running with just several clicks.

Once it's all set up and configured, you use client libraries to interact with Firebase. These libraries are available in all the popular languages.

Supabase is a service that’s getting built as an open-source alternative to Firebase. It’s pursuing similar goals and putting the focus on achieving the same developer experience, but with few implementation differences that are seemingly ticking all the right boxes, and make me very optimistic about its future

  • It's fast - Supabase is reportedly ~3x more performant in read/write operations. The backing PostgreSQL handles massive amounts of data without sacrificing read and write speed.
  • It's secure - They are doing everything to prevent your precious data from attacks and are very proactive towards locating and patching vulnerabilities and even work on the constituent tools to make them more secure.
  • It's reliable - They're putting continued efforts to maximize uptime and ensure reliable data storage

Few other noteworthy things about Supabase

  • It’s relational - Supabase is all-in on trusting community-favorite Postgres for all the storage need. NoSQL won't be the only stoarge style you'll have to settle with anymore.
  • It’s open-source and is composed of tools that are itself battle-tested, enterprise-grade, open-source packages - which makes the overall system very open, transparent, and stable.
  • It’s using a lingo familiar to you - No woes and confusion of terminologies and feature sets offered and no white-labelling makes it very approachable

How Supabase works?

It helps to think of Supabase as a supacapable cloud-based PostgresSQL managed instance. You manage your DB/tables through a web-based interface that lets you run queries through a full-blown Query editor as wells a wizard like UI. The tables you create can later be accessed through client libraries or SDKs. On top of it, you have an authentication layer, and a layer for CRUD updates synchronisation across all the connected clients.

The essential components that shape Supabase are —

Persistence - PostgreSQL, a reliable, robust and very performant object-relational database system is the backing DB engine.

Authentication - The job of authentication is off-loaded to GoTrue, an open-source API written in golang, that can act as a standalone API service for handling user registration and authentication for front-end projects. Based on OAuth2 and JWT it's capable of handling user signup, authentication and custom user data

APIs & DB Management - APIs are powered by PostgREST which is a standalone web server that turns your PostgreSQL database directly into a RESTful API. An open-source library postgres-meta is behind supporting operations like fetching tables, adding roles and queries. PostgREST and pg-api help you fluently build queries for data access and manipulations

All of this is glued and accessed at scale through a open-source API Gateway Kong that Supabase uses to route your requests for access to specific service type. The real-time support and synchronisation is enabled by a Elixir based Realtime server built by the Supabase team.

  • In achieving Firebase like goals, If the Supabase folks don't find something open-source that could support and help them meet their objectives, they build and open-source it.

As long as you're using Supabase just as a consumer these aren't the details you need to bother about. It's all managed transparently BTS, but still, it shows how Supabase is no magic or black-box of things you may not have any clue about in doing day-to-day operational tasks. Being open-source helps Supabase being really approachable for open-source developers and is useful for the rest of us to understand its working, capabilities and limits.

How to Supabase?

Similar to Firebase, Supabase also ships with an official Javascript SDK and the SDKs for C#, Python are provided by commuinty. Few of the modern languages like Dart and Rust are also in the pipeline.

Although there's a SDK to individually interact with the REST APIs, real-time server, authentication layer, etc. individually but supabase-{lang} is the one true SDK you're likely to use more than the feature specific SDKs to interact with all things Supabase.

Setting up a project

Setting up a project is as simple as visiting https://app.supabase.io , signing in and creating Organization → Project → Table through a visual editor(Table View) or a full-blown SQL query editor.

  • Organisation is what cohesively ties all of your related projects.

Once your'e done setting up a project at https://app.supabase.io/ you can interact with the service using your language-level library of choice.

On the client-side, supabase is the instance that you need to configure to talk with Supabase. It takes a public Supabase project URL and a public anon key as parameters

var SUPABASE_URL = '<supabase url - retrieve from supabase dashboard>'
var SUPABASE_KEY = '<client key - retrieve from supabase dashboard>'

var supabase = Supabase.createClient(SUPABASE_URL, SUPABASE_KEY)

and the Supabase library can be imported as a standalone CDN script

<script src="https://unpkg.com/@supabase/supabase-js"></script>
// or
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js"></script>

or a NPM package

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

The keys to configure the Supabase client are available under API → Authentication → Client Keys

Talking with Supabase

Once you have a supabase instance ready, talking with the service is as simple as selecting a table with a from directive, and chain the operations you'd like to perform. If it's not specifically about any operations on the table, like doing some authentication related work it's available on a auth namespace as supabase.auth.

For example, If you have setup a project getting-things-done and have created a table called todos using the following natural, non-adulterated SQL query

create table todos (
  id bigint generated by default as identity primary key,
  user_id uuid references auth.users not null,
  task text check (char_length(task) > 3),
  is_complete boolean default false,
  inserted_at timestamp with time zone default timezone('utc'::text, now()) not null
);

You can use the following syntax to interact with it in a async javascript function


// Fetch all the todos, sorted on id ASC
let { data: todos } = await supabase
            .from("todos")
            .select("*")
            .order("id", { ascending: false });

// Insert a new todo item
let { data: todo } = await supabase
            .from("todos")
            .insert({ task, user_id: user.id })
            .single();

// Update a todo item
let { data: todo } = await supabase
            .from("todos")
            .update({ task: 'See how Supa Supabase is' })
            .eq("id", id)

// Delete a todo item identified by the given id
await supabase.from("todos").delete().eq("id", id);

The SDK offers a fluent API closely modelling the SQL expression style. You select a table using a from function and then call a op-specific function like select, insert, update , delete,etc.

Authentication also follows a similar style and methods like signUp, signIn, user and signOut are exposed on a subabase.auth object. For example, a call for sign up looks like

supabase.auth
    .signUp({email, password})
    .then(({ data, user }) => {
        // data.access_token, data.refresh_token
        // user.email
    })
    .catch((err) => {
        // err.response.text
    })
  • Besides default email/password login there's support for Google, Facebook, Gitlab, Github, Azure, Bitbucket and Magic links too

So, Is Supabase == Firebase really?

No, not yet! Supabase is in active development(Public Beta) currently and few things that don’t have a direct equivalent in Supabase yet are —

  • Firebase Functions
  • Firebase Storage

and few other services.

But, Storage and Functions are in active development and could make their way into the project sometime soon

Closing Thoughts

Although, Supabase cannot store blob or let you write serverless functions(with access to your Supbase context), it feels very ready and stable to support the persistence, querying and real-time data propagation needs. If you're following modern Serverless patterns there are better tools you could always prefer to go with like Vercel or Netflify functions for lambdas, or Cloudinary for Storage which are purpose-built and perfected over time to support these very use cases. Supabase could be a great choice for the serverless functions/lambdas you already use. Obviously, it's new, and it can’t do everything Firebase does, but what it already does do is pretty awesome!

They also recently raised $6m in funding(https://techcrunch.com/2020/12/15/supabase-raises-6m-for-its-open-source-firebase-alternative/) to support their goal

Go give Supabase a shot today and see if you like it. Let me know if this article helped you undertstand Supabase better. I plan to post more articles on integrating Supabase with a UI and service layer in the upcoming few posts.

Thank you for being till the end 🙌 . If you enjoyed this article, or learned something new, support me by clicking the share button below to reach more people and/or give me a follow on Twitter to see some other tips, articles, and things I learn and share there.