Chrysolites Tech Academy

Short-Video App with React Native and Supabase · Course book

Chapter 5: A Back End with Supabase

Pairs with Lesson 5: Connecting Supabase for Accounts and Data

An app that only lives on one phone cannot be social. Accounts, videos, likes, comments and messages must be stored somewhere every user's app can reach, and that "somewhere" needs authentication, a database, file storage and a way to push updates. Building all of that from scratch would take longer than the app itself. This chapter introduces Supabase, a backend as a service built on PostgreSQL, explains why a relational database suits social data, walks through creating a project and connecting the app with environment variables and the Supabase client, and surveys the services the rest of the course uses, with a worked example of why database indexes matter.

Backend as a service

A traditional back end is a server you write and host yourself: it receives requests from the app, checks who is asking, reads and writes a database and returns results. A backend as a service (BaaS) provides those building blocks ready-made. Your app calls them directly through a client library, and you configure rules instead of writing server code.

Supabase packages several services around one PostgreSQL database.

ServiceWhat it providesUsed in this app for
DatabaseA full PostgreSQL database with an automatic APIUsers, videos, likes, comments, followers, chats
AuthenticationSign-up, sign-in, sessions and providersEmail and password accounts
StorageBuckets for files with access rulesVideo files and profile photos
RealtimeLive notifications of database changes and channelsInstant chat messages
Edge functionsSmall server functions when custom logic is neededOptional tasks such as notifications

Because the app talks to the database directly, security rules called row level security policies do the job a server would normally do: they decide, for each row and each user, what may be read, inserted, updated or deleted. Supabase's dashboard warns when a table has no policies, a useful reminder that open tables are readable by anyone with the project's public key.

A backend as a service has trade-offs worth knowing before relying on one. The speed of development is the great advantage: authentication alone, done properly with password hashing, email confirmation, token refresh and password resets, is weeks of careful work. In exchange, you depend on the provider's pricing, limits and availability, and moving to another provider later means rewriting the parts of the app that use its client library. Supabase reduces this risk because its core is standard PostgreSQL: the data, tables and SQL queries can be moved to any other PostgreSQL host. Logic that must never be bypassed, such as charging money or enforcing complex rules across many tables, can still run on a server, in an edge function or as a database function, so a BaaS app is not limited to what the client can safely do.

Why a relational database suits social apps

Social data is full of relationships. A user has many videos; a video has many likes and comments; a like connects one user to one video; a follow connects two users. A relational database stores each kind of thing in its own table and links rows by their ids, called foreign keys. Questions that cross those links, such as "the ten newest videos from people I follow, with each creator's username and the number of likes", are answered by joining tables in a single query.

Storing relationships as rows has a further benefit: each fact is stored once. A user's username lives only in the users table, so changing it updates every video, comment and message that refers to that user, with no copies to keep in step. Constraints enforce the rules automatically: a like must refer to a real video, and a unique constraint on the pair of user and video means a user can like a video only once, whatever bugs the app might contain.

Document databases, which store nested records, can be quicker to start with, but social features tend to need exactly the cross-cutting queries and consistency guarantees that relational databases do well. PostgreSQL also supports JSON columns for the occasional flexible field, giving some of both worlds.

Indexes and fast queries

A database finds rows quickly only if it has an index on the columns being searched. Without one, finding the likes for a particular video means reading every row in the likes table, a sequential scan. With a B-tree index on the video column, the database walks a balanced tree to the matching rows, examining only a handful of pages.

Worked example. A likes table has 1,000,000 rows. A sequential scan examines all 1,000,000 to find one video's likes. A balanced search tree halves the remaining candidates at each step, so finding the first match takes about log2(1,000,000) ≈ 20 comparisons; real B-trees branch hundreds of ways at each level, so they need only three or four page reads. If the table grows to 10,000,000 rows, the scan does ten times the work, while the tree needs only about 23 comparisons, just three more. That is why queries that filter on foreign keys, such as "likes where video id is X", should have an index on that column.
sequential scan indexed search: 10 to 23 101,000100k10M 1k10k100k1M10M rows in the table (log scale)work per lookup (log scale)
Figure 5.1 — Work needed to find rows as a table grows. A scan grows in step with the table; an indexed search grows by a few steps each time the table grows tenfold.

Indexes are not free: each one takes space and slightly slows inserts, because the index must be updated too. The usual guidance is to index the columns used to filter, join and sort frequent queries, and to leave the rest alone. Primary keys are indexed automatically; foreign keys usually are not, so they are worth checking.

Creating the project and connecting the app

Creating a project in the Supabase dashboard takes a minute: choose a name, a database password and a region near your users. The region matters because every request travels there and back: a database on another continent can add a tenth of a second or more to each query. The project's settings then show two values the app needs: the project URL and the public anon key. The anon key is meant to be shipped in apps, because it grants only what the row level security policies allow. The separate service role key bypasses all policies and must never appear in an app; it belongs only on trusted servers.

The two public values go into an .env file at the root of the project, with names that begin with EXPO_PUBLIC_ so that Expo includes them in the app: for example EXPO_PUBLIC_SUPABASE_URL and EXPO_PUBLIC_SUPABASE_ANON_KEY. Listing .env in .gitignore keeps them out of version control, which is good practice even for public keys, because it keeps different environments, such as development and production projects, separate.

import "react-native-url-polyfill/auto";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { createClient } from "@supabase/supabase-js";

export const supabase = createClient(
  process.env.EXPO_PUBLIC_SUPABASE_URL,
  process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY,
  { auth: { storage: AsyncStorage, autoRefreshToken: true, persistSession: true, detectSessionInUrl: false } }
);

This single client, created once in a utils/supabase file and imported wherever it is needed, handles everything: database queries, authentication, storage and real-time subscriptions. On React Native, the session is saved in AsyncStorage, the phone's simple key-value storage, so users stay signed in between launches, and tokens refresh automatically before they expire. The URL polyfill supplies browser features that the library expects but React Native lacks.

Testing the connection and planning the next steps

A quick way to confirm the connection is to create a small test table in the dashboard, add a row and query it from a screen with supabase.from("test").select("*"), logging the result and any error. Every Supabase call returns an object with data and error; checking error on every call, rather than assuming success, makes problems visible immediately. If the query returns an empty list even though the table has rows, the most likely cause is row level security: the table has policies enabled but none allows reading, which is the correct secure default.

With the connection working, the next step is designing the real tables: users, videos, likes, followers, comments and chats, with their relationships. The course uses Prisma to define them in a schema file and push them to the database, which keeps the structure in version control and makes it easy to recreate in a new project. After that, authentication connects Supabase's accounts to the users table, and storage buckets are created for videos and photos.

Practice tasks

  1. A comments table has 4,000,000 rows. About how many comparisons does a balanced binary search need to find one video's first comment, and how many rows does a sequential scan examine?
  2. Explain why the anon key may be included in the app but the service role key must not be.
  3. Write the two environment variable names the app needs, and explain why they begin with EXPO_PUBLIC_.
  4. Describe in words the join needed to show each video with its creator's username.
  5. Why does a unique constraint on the pair of user and video protect the likes table even if the app has a bug?
  6. A test query returns no rows, though the table has data. What is the most likely cause, and how would you check?

Install Chrysolites Tech Academy

Android / Chrome / Edge: open the browser menu and choose Install app or Add to Home screen.

iPhone / iPad (Safari): tap the Share button, then Add to Home Screen.