clouddatabasereal-time

Supabase - Intro to the Open Source Firebase Alternative

Aftab Alam

Aftab AlamMarch 15, 2021

updated: December 07, 2021

14 min read–––

Aftab Alam

While 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, how it works(briefly) 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(or, much better) 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. Trusting PostgreSQL and it's vibrant and inventive community lets Supabase tap into the potential of the huge ecosystem, and do things beyond RESTful CRUD through supported extensions that you can easily enable/disable through their service
  • 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. Not just the tools they rely upon, but also the tools they develop to add features and make thier service more powerful is also eventually open-sourced. For example, besides the libraries/SDKs you'll use to talk with Supabase, you have things like a free UI kit, a grid component, and even the entire PostgreSQL management experience(Supabase Studio) made open-source and available for local development
  • 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. You won't have to learn a new syntax to get data in and out of a database. Either use the SQL you know and love, or use the UI to work with the DB.
  • Supa-focussed on DX - The team's supafocuused in helping developers/you get as efficient as possible, by investing in solutions that let you ship with more confidence. You have a CLI that you can use to develop applications locally, rather than connecting to a live project, and an app Supabase Studio they recently open-sourced to help you connect and work with the local DB effortlessly
  • Supa-inventive - Supabase isn't just trying to be your persistence partner, but building a platform to support most of the sought-after modern app needs like authentication, storage, logging, CDN, etc. too.

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, etc.

The essential components that shape Supabase are —

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

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

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.

Storage - Supabase allows for media storage/management through a Fastify based stroage API server that's backed by AWS S3.

PostegreSQL is like the foundational persitence layer that acts as a brain for the user data, authentication details, permissions, media details, etc.

All of the services are 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.

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 ships with an official Javascript SDK. SDKs for other languages like C#, Python, etc. are provided by commuinty. Few of the modern languages like Dart and Rust are also in the pipeline. The full list of community supported SDKs is available here.

Although there's a SDK to individually interact with the auto-generated REST APIs, real-time server, authentication layer, storage 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

How to CRUD 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.

How to perform Auth/Z with Supabase?

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

// Create a new user.
const { user, session, error } = await supabase.auth.signUp({
  email: 'example@email.com',
  password: 'example-password',
})
// Log in an existing user, or login via a third-party provider.
const { user, session, error } = await supabase.auth.signIn({
  email: 'example@email.com',
  password: 'example-password',
})
// Sign-out
const { error } = await supabase.auth.signOut()

Besides the default email/password login Supabase currently supports 14 3rd Party oAuth providers(and growing) including the popular ones like Google, Facebook, Github, Apple, Twitter, Slack and Magic links too. All of these could be used through a simple app configuration step in the provider service, Supabase service, and a simple use as follows

const { user, session, error } = await supabase.auth.signIn({
  // provider can be 'github', 'google', 'gitlab', or 'bitbucket'
  provider: 'github'
})

For a full list of supported oAuth providers and integration guides visit here

How to use Supabase for storage?

Supabase leverages AWS S3 for storing the media files you upload through the client SDKs or the Web UI. You'll find the full suite of methods, built around the functions(and familiar sounding) you perform in S3 around buckets [create|get|list|update|delete|empty]Bucket(s) and files using a supabase.storage namespace.

For example, to create a bucket for user avatars you'd just do

const { data, error } = await supabase
  .storage
  .createBucket('avatars', { public: false })

where avatars is the unique identifier for the bucket you are creating. Once created you can use

const { data, error } = await supabase
  .storage
  .getBucket('avatars')

to retrieve the details of the bucket. Similary, to update you'd invoke a supabase.storage.updateBucket('avatars', { public: false }) or to delete you'd call supabase.storage.deleteBucket('avatars').

To put files inside the bucket you'd use the supabase.storage.from namespace like

const avatarFile = event.target.files[0]
const { data, error } = await supabase
  .storage
  .from('avatars')
  .upload('public/avatar1.png', avatarFile, {
    cacheControl: '3600',
    upsert: false
  })

Refer the storage API docs to know about all the methods available.

One very interesting feature of the JS SDK is that it's universal. It works equally well in the browser, as well as on the server/Node.js

So, Is Supabase == Firebase really?

When I initially wrote this article(March, this year), Supabase didn't support Storage or had much visibility around functions. Today, Supabase supports Storage, Function Hooks/Triggers(alpha) and have opened RFCs for community participation in providing the ultimate "function"(cloud functions like Firebase, Vercel, Netlify) experience.

That's not it. In the very recent launch week, Supabase announced CDN(with TLS1.3, HTTP/3, Brotli) and revealed their future plans to support GraphQL. They also acquired Logflare, a log ingestion platform to natively support things like debugging, observability, analytics, etc. through SQL.

Supabase doesn't ships with as many sub-services as Firebase, but it does have some of the same core offerings like CRUD, auth, storage, etc. A comparison with Firebase lets you see things with perspective of an already known solution, but as exemplified by it's releases, announcements, and contributions feels a more open, robust, generic, extensible, and ambitious service. Though you have no parallels for the offerings like FCM, Analytics, A/B Testing, etc. you can always mix, and integrate with multiple providers as per your needs. If you're following modern Serverless patterns, need functions today, or having custom media management needs, 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.

Obviously, it's relatively new, and it can’t do everything Firebase does, but what it already does do is pretty awesome!

The future looks bright for Supabase and the products that are looking forward to have a solid, yet easily approachable foundation for their apps. Supabase raised $6m(https://techcrunch.com/2020/12/15/supabase-raises-6m-for-its-open-source-firebase-alternative/) last year, and recently raised $30M in funding to support their goal and build a world-class solution.

References

If you're convinced to empower your apps with Supabase here are few of the references you could follow

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.

Tweet about this post(by clicking the button above) or like/re-tweet one of the tweets that shares this article, and it will show up here eventually