Saving is off. The course database is down: labs work for practice, but nothing is saved.The course database is down.

LAB06

Storage in React Native — AsyncStorage, SQLite, SecureStore and Supabase

Where an app keeps its data, and why: key-value storage (AsyncStorage, MMKV), a SQLite database on the phone, secure storage for tokens, and a Supabase cloud database with sign-in, file storage, Row Level Security and Realtime. Then the phone and the cloud work together, even offline. Real screenshots of the phone and the Supabase dashboard in every part, and 18 checked exercises build the parts of one offline-ready tasks app.

Intermediate 3 hasyncstoragemmkvsqlitesecurestoresupabasesupabase-authrow-level-securityrealtimeoffline-sync

Your progress

0 / 18 exercises

7 parts · 3 h

Before you start

Who’s doing Lab 06?

This lab is open any time. Enter your name and student ID to start. Your work is saved.

By the end you will

  • Explain how an app keeps data — memory or storage, phone or cloud, key-value or database, files — and choose the right place for each piece of data
  • Save and read data with AsyncStorage (as JSON text) and with MMKV, and say when to choose each one
  • Create a SQLite table on the phone and run INSERT, SELECT, UPDATE and DELETE with ? parameters
  • Keep tokens in SecureStore, and explain why AsyncStorage is not safe for secrets
  • Connect an app to Supabase with the project URL and the publishable key, and read, add, change and delete rows
  • Upload a file to Supabase Storage and show it with a public or a signed URL
  • Explain Supabase Auth sessions and Row Level Security, and write a policy
  • Create a Supabase project and find your way in its dashboard: API keys, Table Editor, SQL Editor, Authentication, Storage, Realtime and Logs
  • Show new rows on the phone the moment they are added, with Supabase Realtime
  • Read a Supabase error code and find the fix
  • Keep data available offline and send it to the cloud later, without duplicates

You need

  • Lab 05 completed: fetch, async / await and JSON
  • React Native basics: components, useState, useEffect
  • For Part 5: a free Supabase account (sign up at supabase.com with GitHub or an email)

Part 1: Where your app keeps data

14 min

In Lab 05 your app got data from a server. When the app closed, everything it had in its variables was gone. Storage means writing data somewhere it stays, so the app can read it again later.

What “closed” means: when the user swipes the app away, or the phone restarts, the phone ends the app. Everything the app kept in memory — its variables and every useState — is deleted. What the app wrote to the phone’s disk stays. Only deleting the app deletes its files too.

memory

Memory

useState and variables. Fast, but it is emptied when the app closes. Use it for what the screen needs right now.

persistent

Persistent storage

Written to the phone’s disk (or a server). It is still there after the app closes and opens again.

local

Local storage

On this phone only. Works with no internet. Gone if the app is deleted.

cloud

Cloud storage

On a server. Every phone of the user (and other users) can reach it — but only when online.

Data also has a shape:

key-value

Key-value

One value under one name (the key): theme → dark. Simple and small. AsyncStorage and MMKV (Part 2).

relational

A relational database

Tables of rows and columns that you search with SQL: “tasks not done, newest first”. SQLite (Part 3) and Postgres in Supabase (Part 5).

files

File storage

Whole files: a photo, a PDF. They are bytes, not rows. Supabase Storage (Part 5).

Two more words you will meet in every part:

  • Synchronous means the answer comes back at once (MMKV). Asynchronous means the answer comes later, so you write await (AsyncStorage, SQLite, SecureStore, Supabase).
  • Storage keeps text, not JavaScript objects. Serialize = turn an object into text with JSON.stringify. Deserialize = turn the text back into an object with JSON.parse.

Press Save some data, then try the other buttons. Click any place to read what it is for.

On the phone

In the cloud (Supabase)

Phone or cloud?
WhatOn the phonelocalIn the cloudSupabase
Works with no internetYesbetter hereNo
SpeedVery fast: no networkbetter hereA request over the internet
Other phones see itNoYesbetter here
Deleting the appDeletes the dataThe data staysbetter here
Who protects itThe phone (and you, for secrets)The server: sign-in and Row Level Security

Which one would you use?

  1. The user’s profile must be the same on their phone and their tablet.
  2. The app must show today’s tasks on the bus, with no signal.
  3. Remember that the welcome screen was already seen.
● LIVE DEMOMemory or storage: what survives a restart?Loading the editor and preview…

The same app on a real Android phone. Left: after pressing the button three times. Right: after closing the app and opening it again.

The counter app on an Android phone: in memory 3, saved 3, after pressing the button three times

Before closing

The same app after it was closed and opened again: in memory 0, saved still 3

After opening it again

useState started again from 0. The number in AsyncStorage was read back from the disk: still 3.

EX 01Where should this data live?Loading the exercise…

Checkpoint

You can say, for any piece of data, whether it belongs in memory, key-value storage, a database, secure storage, files, or the cloud — and why.

Part 2: Key-value storage: AsyncStorage and MMKV

30 min

AsyncStorage saves text under a key, on the phone. It exists because React Native has no built-in way to keep small data between launches. It is asynchronous (every call needs await), it is not encrypted, and it is included in Expo Go.

Terminal — install
npx expo install @react-native-async-storage/async-storage
import AsyncStorage from '@react-native-async-storage/async-storage';

await AsyncStorage.setItem('settings', JSON.stringify({ dark: true, size: 18 })); // save (object → text)
const text = await AsyncStorage.getItem('settings');           // read: the text, or null
const settings = text ? JSON.parse(text) : null;                // text → object
await AsyncStorage.mergeItem('settings', JSON.stringify({ size: 20 })); // update one field
await AsyncStorage.removeItem('settings');                      // remove one key
await AsyncStorage.clear();                                     // remove every key of this app
const keys = await AsyncStorage.getAllKeys();                   // which keys exist

In your app: an object

{ dark: true, size: 18 }

JSON text (a string)

—

On the phone: AsyncStorage

keyvalue
settings(nothing yet)
const settings = { dark: true, size: 18 };
const text = JSON.stringify(settings);        // object → text
await AsyncStorage.setItem('settings', text); // the phone keeps text
const saved = await AsyncStorage.getItem('settings'); // text, or null
const back = JSON.parse(saved);               // text → object

Press Save: watch the object become text, then a row on the phone.

Where is it on the phone? On Android, AsyncStorage keeps every key in one small SQLite database file named RKStorage, in the app’s private folder. On iOS it is a file in the app’s folder. Other apps cannot open these folders. But anyone who copies the app’s files (from a backup, or a rooted phone) can read them, because the values are not encrypted. In Expo Go, each project gets its own storage, so two projects never see each other’s keys.

Reading and saving can fail (a full disk, a broken value), so put them in try / catch:

try {
  const text = await AsyncStorage.getItem('settings');
  if (text) setSettings(JSON.parse(text)); // JSON.parse throws if the text is broken
} catch (error) {
  console.warn('Could not load the settings', error); // the app keeps its defaults
}

Use AsyncStorage for

  • settings: theme, language, text size
  • small flags: “seen the welcome screen”
  • a small cache of the last screen

Do not use it for

  • tokens and passwords: it is a plain file (Part 4)
  • hundreds of rows you search or sort (Part 3)
  • anything other phones must see (Part 5)
● LIVE DEMOEvery AsyncStorage call, one button eachLoading the editor and preview…
EX 02What does storage give back?Loading the exercise…
EX 03Settings that survive a restartLoading the exercise…

The settings screen of Exercise 3 on a real phone, after it was closed and opened again. The dark theme and the text size were read back from AsyncStorage when the app started:

  1. The theme, read back with getItem and JSON.parse when the app starts
  2. The text size: a number inside the same JSON text

MMKV is another key-value store. It is written in C++, it reads and writes synchronously (no await), and it keeps types: a number comes back as a number. It is much faster than AsyncStorage when an app reads values very often. It is native code, so it needs a development build — it does not run in Expo Go.

Terminal — install MMKV (development build)
npx expo install react-native-mmkv react-native-nitro-modules
npx expo prebuild
npx expo run:android
Expo Go cannot load it: from now on you open the development build instead

This is what Expo Go shows when an app uses MMKV. Expo Go is a ready-made app with a fixed set of native code, and MMKV’s native part (NitroModules) is not in it. A development build is your own version of that app, built on your PC, with every native package your project needs:

Expo Go on Android showing Something went wrong: Failed to get NitroModules, the native module could not be found

Read the first line of the error: Failed to get NitroModules … could not be found. The native part is missing, so the fix is a development build, not a change in your code.

AsyncStorage or MMKV?
WhatAsyncStorageExpo GoMMKVdevelopment build
ReadingLater: await getItem(key)At once: getBoolean(key)better here
TypesText only (JSON for objects)Text, numbers, booleans, bytesbetter here
SpeedFine for a few readsMuch faster for many readsbetter here
SetupWorks in Expo Gobetter hereNeeds a development build
EncryptionNoneOptional encryptionKey (but the key must be stored safely)
Secrets (tokens)NoNo: use SecureStore

AsyncStorage

const text = await AsyncStorage.getItem('dark');
const dark = text === 'true';
await AsyncStorage.setItem('dark', String(!dark));

MMKV

const storage = createMMKV();
const dark = storage.getBoolean('dark') ?? false;
storage.set('dark', !dark);

Which one would you use?

  1. A class project that you test in Expo Go, saving the theme.
  2. A reading app that reads the font size and position on every page turn.
EX 04The same setting with MMKVLoading the exercise…

Checkpoint

Settings survive a restart: saved as JSON text with AsyncStorage, or as typed values with MMKV. Neither one is a place for secrets.

Part 3: A database on the phone: SQLite

27 min

A database keeps data in tables. A table has columns (the fields, each with a type) and rows (one row per thing, for example one task). The primary key is a column whose value is different in every row, usually id, so one row can always be found.

Key-value storage is not enough when the data is a list you search. To show “tasks not done, newest first” with AsyncStorage you would load the whole list, JSON.parse it, filter and sort it in JavaScript, and save the whole list again after every change. A database does it with one query, and changes one row at a time.

SQLite is a database in one file on the phone. You talk to it with SQL, a language of short statements:

Run one statement at a time

loading SQLite…

Key-value or SQLite?
WhatKey-value (AsyncStorage)SQLite
ShapeOne value per keyTables of rows and columnsbetter here
Find some itemsLoad everything, filter in JavaScriptSELECT … WHERE …better here
Change one itemSave the whole list againUPDATE … WHERE id = ?better here
SetupNo setupbetter hereCREATE TABLE first
Best forA few settingsMany rows of the same shape

Which one would you use?

  1. Save the user’s language.
  2. A notes app: 500 notes, searched by title and sorted by date.

Every column has a type. SQLite has four: INTEGER (whole numbers), REAL (decimals), TEXT and BLOB (bytes). There is no true/false type: store 1 for true and 0 for false in an INTEGER column, like done below. Dates are stored as TEXT, for example 2026-11-16T09:00:00Z.

In Expo, use expo-sqlite. It is included in Expo Go.

Terminal — install
npx expo install expo-sqlite

The database code belongs in its own file, db.ts. Screens only call its functions (addTask, getTasks…) and never write SQL themselves.

db.tsStep 1 of 5
import * as SQLite from 'expo-sqlite';
 
export const dbPromise = SQLite.openDatabaseAsync('tasks.db');
 
export async function setup() {
  const db = await dbPromise;
  await db.execAsync(`
    PRAGMA journal_mode = WAL;
    CREATE TABLE IF NOT EXISTS tasks (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      title TEXT NOT NULL,
      done INTEGER NOT NULL DEFAULT 0
    );
  `);
}
 
export async function addTask(title: string) {
  const db = await dbPromise;
  const result = await db.runAsync('INSERT INTO tasks (title) VALUES (?)', title);
  return result.lastInsertRowId;
}
 
export async function getOpenTasks() {
  const db = await dbPromise;
  return db.getAllAsync('SELECT * FROM tasks WHERE done = ? ORDER BY id DESC', 0);
}
 
export async function addMany(titles: string[]) {
  const db = await dbPromise;
  await db.withTransactionAsync(async () => {
    for (const title of titles) {
      await db.runAsync('INSERT INTO tasks (title) VALUES (?)', title);
    }
  });
}

openDatabaseAsync opens the file tasks.db (and creates it the first time). Every function waits for this one connection.

● LIVE DEMOA first SQLite databaseLoading the editor and preview…
EX 05What does each SQL line do?Loading the exercise…
EX 06A tasks database on the phoneLoading the exercise…

The tasks app of Exercise 6 on a real phone. Each line on the screen is one row of the tasks table in the file tasks.db:

  1. Add runs runAsync('INSERT INTO tasks (title) VALUES (?)', title): one new row
  2. Ticking sets done = 1 with one UPDATE … WHERE id = ?

Close the app and open it again: the list is read back from tasks.db with getAllAsync.

Checkpoint

Your tasks live in a real SQLite table on the phone. You can explain tables, rows, columns, the primary key, ? parameters, WHERE, and why a transaction saves all or nothing.

Part 4: Secrets: secure storage

20 min

Sensitive data is data that lets someone act as the user or harms them if it leaks: tokens, keys, personal information. When a user signs in, the server gives the app tokens:

short-lived

Access token

Proof of who the user is, sent with every request. It stops working after a short time (Supabase: about 1 hour).

long-lived

Refresh token

Used to get a new access token without asking for the password again. Whoever has it can stay signed in as the user.

AsyncStorage keeps them as plain text. Encryption at rest means the data is stored encrypted, so the file is unreadable without a key. On iOS the Keychain, and on Android the Keystore, keep that key inside the phone’s secure hardware. Expo SecureStore uses them for you.

AsyncStorage · a plain file in the app’s folder

(empty)

SecureStore · Keychain (iOS) / Keystore (Android)

(empty)

The key that opens it stays inside the phone’s secure hardware. Only your app can ask for the value.

Save the token in both places, then press Someone copies the app’s files.

AsyncStorage or SecureStore?
WhatAsyncStorageSecureStore
On diskPlain textEncryptedbetter here
SizeFine for settings and small databetter hereSmall values only (some iOS versions refused values above about 2048 bytes)
KeysAny textLetters, numbers, ., -, _
Use it forSettingsTokens and keysbetter here

AsyncStorage

await AsyncStorage.setItem('token', token);

SecureStore

await SecureStore.setItemAsync('auth.token', token);

Which one would you use?

  1. The refresh token after sign-in.
  2. The app’s language.
Terminal — install
npx expo install expo-secure-store
included in Expo Go
import * as SecureStore from 'expo-secure-store';

await SecureStore.setItemAsync('auth.token', token);            // save (encrypted)
const token = await SecureStore.getItemAsync('auth.token');     // read: the value, or null
await SecureStore.deleteItemAsync('auth.token');                // delete (sign out)
// values are strings: JSON.stringify an object first. Keep them small.

react-native-keychain does the same job with more options (for example asking for the fingerprint). It is native code, so it needs a development build:

import * as Keychain from 'react-native-keychain';

const options = { service: 'com.example.session' };
await Keychain.setGenericPassword('session', token, options);
const credentials = await Keychain.getGenericPassword(options); // false, or { username, password }
await Keychain.resetGenericPassword(options);

Common mistakes

  • a token in AsyncStorage
  • console.log(token): logs are copied to tools and crash reports
  • a secret key in EXPO_PUBLIC_…: it is built into the app
  • saving the password “to sign in again”

What secure storage does not do

  • it protects the token on the phone, at rest
  • it does not decide what the user may do: the server must check every request
  • in Part 5, Row Level Security is that check
● LIVE DEMOThe same token, plain and encryptedLoading the editor and preview…

On a real phone the app reads back the same token from both places: the difference is only on the disk. AsyncStorage wrote it as plain text; SecureStore wrote unreadable bytes and keeps the key in the Android Keystore:

An Android app that saved the same token in AsyncStorage and in SecureStore and reads both back

Your app always gets the real value back. Someone who copies the files does not: that is what “encrypted at rest” protects against.

EX 07Who can read the token?Loading the exercise…
EX 08A token service with SecureStoreLoading the exercise…

Checkpoint

Tokens go to SecureStore with three calls, and stay out of AsyncStorage, logs and EXPO_PUBLIC_ variables. The server still checks every request.

Part 5: The cloud: Supabase

68 min

Supabase is a backend you do not have to write. One project gives you a Postgres database, Auth (sign-in), Storage (files in buckets), Row Level Security (rules inside the database that decide which rows each user may touch) and Realtime (changes sent to the phones that listen). Your app talks to it with the supabase-js library.

Every section below shows the real Supabase dashboard first, then the code, then an exercise.

Your appsupabase-js on the phone

Your Supabase project

API gatewaychecks the apikey
Authusers and sessions
Database APIrequest → SQL
Row Level Securitya policy for every row
Postgresthe tables
Storagebuckets of files

The request

Choose a request above.

The answer

—

Each button sends one request. Watch which parts of Supabase it passes through.

A. Create your project

Start this first: a new project takes about two minutes to be ready, and you can read on meanwhile.

The words on this form:

  • An organization groups your projects. A free account starts with one.
  • A project is one backend: one database, one Auth, one Storage, one set of keys. One app usually needs one project.
  • The database password is for connecting to Postgres directly (from a server or a database tool). The app never uses it. Press Generate a password and keep it in a password manager.
  • The region is where the computer that runs your project is. Choose the one closest to your users: for Egypt, Central EU (Frankfurt).
  • A free project pauses after about a week with no use. Open it in the dashboard to start it again.
  • A free account can have 2 active projects. The form refuses a third: pause or delete one first (Project Settings → General).

The form also has two switches under Security: Enable Data API (on: supabase-js needs it) and Enable automatic RLS (turns Row Level Security on for every new table — a good habit).

B. Keys: publishable and secret

When the project is ready, copy two values from Project Settings → API Keys (the Connect button at the top shows them too):

Project URL

https://<project-ref>.supabase.co. Safe in the app.

Publishable key

sb_publishable_…. Made for apps: it reaches only what Row Level Security allows.

Secret key

sb_secret_… (the old name: service_role). It skips Row Level Security. Never put it in an app, a .env with EXPO_PUBLIC_, or Git.

The API Keys page of the Supabase dashboard with the publishable key shown and the secret key hidden

The publishable key is shown in full. The secret key stays hidden until you press its eye button: it is meant for servers only. (The project’s own values are blurred in this picture.)

The page also says Legacy API keys will be retired in early 2027: the old anon and service_role keys are being replaced by these two kinds.

Why is the publishable key safe in an app? It only says which project the request is for. It does not say who sends it. A request with only the publishable key is treated as anon (nobody signed in). What anon and signed-in users may do is decided by Row Level Security, in section F.

Terminal — install
npx expo install @supabase/supabase-js react-native-url-polyfill expo-sqlite

The two values go in a file named .env in the project folder. Expo copies every variable that starts with EXPO_PUBLIC_ into the app (restart npx expo start after you change it):

EXPO_PUBLIC_SUPABASE_URL=https://<project-ref>.supabase.co
EXPO_PUBLIC_SUPABASE_PUBLISHABLE_KEY=sb_publishable_…
lib/supabase.tsStep 1 of 4
import 'react-native-url-polyfill/auto';
import { createClient } from '@supabase/supabase-js';
import 'expo-sqlite/localStorage/install';
 
const supabaseUrl = process.env.EXPO_PUBLIC_SUPABASE_URL!;
const supabasePublishableKey = process.env.EXPO_PUBLIC_SUPABASE_PUBLISHABLE_KEY!;
 
export const supabase = createClient(supabaseUrl, supabasePublishableKey, {
  auth: {
    storage: localStorage,
    autoRefreshToken: true,
    persistSession: true,
    detectSessionInUrl: false,
  },
});

React Native does not have the full URL class that supabase-js uses: this line adds it.

EX 09Keys and parts of SupabaseLoading the exercise…

C. Tables: Table Editor or SQL Editor

There are two ways to make a table. Both make the same table:

click

Table Editor

Add columns with a form: name, type, default. Good for looking at your rows and changing one by hand.

type

SQL Editor

Paste SQL and press Run. Good for many steps at once, and you can keep the SQL in your project (supabase/schema.sql) to run again in a new project.

In the dashboard: SQL Editor → New query, paste, Run:

SQL EditorStep 1 of 5
create table public.tasks (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null default auth.uid() references auth.users (id) on delete cascade,
  title text not null check (char_length(title) > 0),
  done boolean not null default false,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);

uuid: a long random id, made by the database with gen_random_uuid(). In Part 6 the phone makes the id itself.

Supabase checks the SQL before it runs. A create table without Row Level Security gets this warning. Choose Run and enable RLS:

The Supabase SQL Editor warning Potential issue detected: this query creates a table without enabling Row Level Security, with the buttons Run without RLS and Run and enable RLS

Run and enable RLS creates the table with Row Level Security already on: nobody reaches it until you write policies (section F).

The Supabase SQL Editor with the create table statement for tasks and the result Success. No rows returned

“Success. No rows returned” is the right answer: create table makes a table, it does not read rows.

D. Rows: select, insert, update, delete

Every call returns { data, error }. Check error first.

// read: an array of rows (filters and order are optional)
const { data, error } = await supabase.from('tasks').select('*').eq('done', false).order('created_at');

// add: no rows come back unless you chain .select()
const { error: addError } = await supabase.from('tasks').insert({ title: 'Buy milk' });
const { data: created } = await supabase.from('tasks').insert({ title: 'Read' }).select().single();

// change and remove: always with a filter, so only the rows you mean change
await supabase.from('tasks').update({ done: true }).eq('id', task.id);
await supabase.from('tasks').delete().eq('id', task.id);

if (error) console.warn(error.code, error.message); // e.g. 42501 = blocked by Row Level Security
● LIVE DEMOTalk to the practice Supabase projectLoading the editor and preview…
EX 10Tasks in the cloudLoading the exercise…

After the app added tasks, they are in Table Editor → tasks. Every row has the user_id of the user who added it:

The Supabase Table Editor showing the tasks table with three rows added from the phone app: Buy milk, Call Omar and Read Part 6 of the lab, all with the same user_id

Three tasks sent from a real phone: one row each, all with the same user_id. The bar shows 4 RLS policies and Role postgres: the dashboard reads as the project’s owner, so it sees every row.

E. Auth: users and sessions

Supabase Auth checks the email and password and answers with a session: the access token and the refresh token. supabase-js keeps the session in auth.storage (so the user stays signed in after a restart) and sends the access token with every request.

await supabase.auth.signUp({ email, password });                 // new account
const { data, error } = await supabase.auth.signInWithPassword({ email, password });
const { data: { session } } = await supabase.auth.getSession();  // the saved session, or null
const { data: listener } = supabase.auth.onAuthStateChange((event, session) => {
  // INITIAL_SESSION, SIGNED_IN, SIGNED_OUT, TOKEN_REFRESHED…: update the screen
});
listener.subscription.unsubscribe(); // in the useEffect cleanup
await supabase.auth.signOut();

Try every step, in any order:

On the phone

No session: nobody is signed in.

Saved in auth.storage

(nothing)

Supabase Auth (in the cloud)

No user with this email.

Last request

—

onAuthStateChange(event, session)

  1. INITIAL_SESSION · session: null

Press Sign up. Then try the other buttons in any order.

Confirm email. A new project asks every new user to confirm their email address: signUp creates the user and sends an email, but returns no session until the user opens the link. For a class project you can turn it off in Authentication → Sign In / Providers, section User Signups: switch off Confirm email and press Save changes. Then signUp signs the user in at once.

Supabase Authentication, Sign In / Providers, User Signups: Allow new users to sign up on, anonymous sign-ins off, Confirm email off, and Save changes

Confirm email is off in this practice project, so a new user is signed in as soon as they sign up. Leave it on in a real app.

Users. Authentication → Users lists every account: its email, when it was created and when it last signed in. You can add a user here (tick Auto Confirm User) or delete one. Passwords are never shown: Supabase keeps only a scrambled form of them (a hash).

The Users page of Supabase Authentication with the Add user button and one test user

Add user (top right) creates an account by hand. This practice project’s only user signed in as a guest, so its provider type is Anonymous and it has no email; your users will show their email here.

Keeping the session fresh. The access token works for about one hour. supabase-js gets a new one with a timer before it runs out. On a phone, that timer should only run while the app is on the screen — this is in Supabase’s Expo guide:

App.tsxRefresh only while the app is openStep 1 of 2
import { AppState } from 'react-native';
import { supabase } from './lib/supabase';
 
// refresh the session only while the app is on the screen
AppState.addEventListener('change', (state) => {
  if (state === 'active') supabase.auth.startAutoRefresh();
  else supabase.auth.stopAutoRefresh();
});

AppState tells you whether the app is on the screen (active) or in the background.

The quickstart keeps the session in localStorage, which is not encrypted. The session holds the refresh token — a secret (Part 4). Supabase’s Expo tutorial shows how to keep it encrypted, and the final project does exactly that:

lib/largeSecureStore.tsAn encrypted session storeStep 1 of 3
class LargeSecureStore {
  private async _encrypt(key: string, value: string) {
    const encryptionKey = crypto.getRandomValues(new Uint8Array(256 / 8));
    const cipher = new aesjs.ModeOfOperation.ctr(encryptionKey, new aesjs.Counter(1));
    const encryptedBytes = cipher.encrypt(aesjs.utils.utf8.toBytes(value));
    await SecureStore.setItemAsync(key, aesjs.utils.hex.fromBytes(encryptionKey));
    return aesjs.utils.hex.fromBytes(encryptedBytes);
  }
 
  async setItem(key: string, value: string) {
    const encrypted = await this._encrypt(key, value);
    await AsyncStorage.setItem(key, encrypted);
  }
 
  async getItem(key: string) {
    const encrypted = await AsyncStorage.getItem(key);
    if (!encrypted) return encrypted;
    return this._decrypt(key, encrypted); // reads the key from SecureStore
  }
}

A new random AES-256 key for each value. The value is encrypted with it, and the small key goes to SecureStore (encrypted by the phone).

EX 11Sign in, stay signed in, sign outLoading the exercise…

F. Row Level Security

The publishable key is inside every copy of your app, so anyone can call your project’s API. Row Level Security (RLS) makes the database decide, for every row and every request, what this user may do. Checks in your app’s code are not enough: anyone can send requests without your app.

Pick a user, an action and the rules, and watch which rows pass:

Who sends the request?
What does the app do?
Rules on the tasks table

The app sends

Postgres checks

owner (user_id)titlethe rule for this rowresult

One policy per action. Run this in the SQL Editor after the table:

SQL EditorThe four policies of the tasks tableStep 1 of 5
alter table public.tasks enable row level security;
 
create policy "Read own tasks" on public.tasks
  for select to authenticated
  using ( (select auth.uid()) = user_id );
 
create policy "Add own tasks" on public.tasks
  for insert to authenticated
  with check ( (select auth.uid()) = user_id );
 
create policy "Edit own tasks" on public.tasks
  for update to authenticated
  using ( (select auth.uid()) = user_id )
  with check ( (select auth.uid()) = user_id );
 
create policy "Delete own tasks" on public.tasks
  for delete to authenticated
  using ( (select auth.uid()) = user_id );

RLS on: from now on nothing is allowed through the API until a policy allows it.

for selectto authenticatedusing ( … )with check ( … )(select auth.uid())
  1. for selectthe operation it allows
  2. to authenticatedonly signed-in users
  3. using ( … )checked for every existing row: which rows they may see or change
  4. with check ( … )checked for every new or changed row: may it be saved?
  5. (select auth.uid())the id of the user who sent the request

In the dashboard, Database → Policies lists every table: whether RLS is on, and each policy with its command (SELECT, INSERT, UPDATE, DELETE) and the roles it applies to. It also offers to turn RLS on automatically for every new table.

Supabase Database, Policies: the tasks table with RLS enabled and its four policies Add, Delete, Edit and Read own tasks for INSERT, DELETE, UPDATE and SELECT, applied to authenticated

The four policies of section F, one per command, all for authenticated. Disable RLS would open the table to every request: never do it for private data.

Two things that surprise everyone:

  • A read that RLS blocks is not an error: you get data: [] and error: null. An empty list often means “not signed in” or “no select policy”.
  • The SQL Editor and the Table Editor run as the project’s owner, so they skip RLS and show every row. Test your policies from the app.
EX 12Debug Row Level SecurityLoading the exercise…
EX 13What does each policy allow?Loading the exercise…

G. Storage: files in buckets

A bucket is a folder for files. A public bucket gives each file a fixed URL anyone can open: right for profile photos. A private bucket gives signed URLs that stop working after the number of seconds you choose: right for personal documents. Storage has its own policies; a common rule is “each user writes only in the folder named after their id”.

SQL EditorA public bucket, one folder per userStep 1 of 3
insert into storage.buckets (id, name, public)
values ('avatars', 'avatars', true);
 
create policy "Add to your own folder" on storage.objects
  for insert to authenticated
  with check ( bucket_id = 'avatars'
    and (storage.foldername(name))[1] = (select auth.uid())::text );
 
create policy "See your own folder" on storage.objects
  for select to authenticated
  using ( bucket_id = 'avatars'
    and (storage.foldername(name))[1] = (select auth.uid())::text );
 
create policy "Replace in your own folder" on storage.objects
  for update to authenticated
  using ( bucket_id = 'avatars'
    and (storage.foldername(name))[1] = (select auth.uid())::text );

Creates the bucket avatars. public = true: anyone with a file’s URL can open it (no policy needed to view it).

import { decode } from 'base64-arraybuffer';

// the picker gives the photo as base64 text (base64: true); Storage wants bytes
const result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ['images'], base64: true });
const photo = result.assets![0];
const path = userId + '/avatar.png';

const { error } = await supabase.storage
  .from('avatars')
  .upload(path, decode(photo.base64!), { contentType: 'image/png', upsert: true });

const { data } = supabase.storage.from('avatars').getPublicUrl(path);   // public bucket
const { data: signed } = await supabase.storage.from('documents').createSignedUrl(path, 60); // private, 60 s
await supabase.storage.from('avatars').remove([path]);
Supabase Database or Supabase Storage?
WhatDatabaseStorage
HoldsRows: text, numbers, datesFiles: photos, PDFs, videos
Read withfrom(table).select()A URL, or download(path)
Protected byRLS policies on the tableBucket type + policies on storage.objects
Togetherkeeps the file’s path in a column……and Storage keeps the file itself

Which one would you use?

  1. A user’s profile photo.
  2. The task title and whether it is done.
Supabase Storage showing the public avatars bucket with a folder named after a user id that holds avatar.png

The path is the folder (the user’s id) and the file name. The bucket is marked Public, so the file has a fixed URL.

EX 14Upload a profile photoLoading the exercise…

H. Realtime: changes sent to the phone

Until now the phone asked for the rows (select). With Realtime, Supabase tells the phone when a row changes. The phone opens a channel — a connection that stays open — and says what it wants to hear, for example “new rows in tasks”. When a row is added (by this phone, by the same user’s tablet, or in the dashboard), Realtime sends it to every phone that listens.

Four rules:

  1. A table sends changes only if it is in the supabase_realtime publication. Turn it on once, in the SQL Editor: alter publication supabase_realtime add table public.tasks; — or in Database → Publications → supabase_realtime.
  2. RLS still applies: a phone only receives rows its user may read.
  3. Realtime does not keep changes for later. A phone that was offline must load the list again with select when it is back (Part 6 does this).
  4. Close what you open: remove the channel in the useEffect cleanup, or every visit to the screen adds one more listener.
The supabase_realtime publication in the Supabase dashboard with the tasks table switched on

Mona’s tablet

  • Read Part 5 of the lab

Database

tasks · INSERT saves the row

Realtime

who may see this row (RLS)? which phones listen?

Mona’s phone

  • Read Part 5 of the lab

The phone’s code

useEffect(() => {
  const channel = supabase
    .channel('my-tasks')
    .on('postgres_changes',
      { event: 'INSERT', schema: 'public', table: 'tasks' },
      (payload) => setTasks((list) => [...list, payload.new as Task]))
    .subscribe();
  return () => { supabase.removeChannel(channel); };
}, []);

The payload the callback gets

—

Press Mona adds a task on her tablet and watch the phone.

TaskList.tsxListen for new tasksStep 1 of 4
useEffect(() => {
  const channel = supabase
    .channel('my-tasks')
    .on(
      'postgres_changes',
      { event: 'INSERT', schema: 'public', table: 'tasks' },
      (payload) => setTasks((list) => [...list, payload.new as Task]),
    )
    .subscribe((status) => console.log('realtime:', status));
 
  return () => {
    supabase.removeChannel(channel);
  };
}, []);

channel('my-tasks') makes a channel. The name is yours: it only has to be different from your other channels.

EX 15A list that updates by itselfLoading the exercise…

I. Logs and errors

When something fails, read error first. The code says where to look:

You getIt meansLook at
error.code 42501RLS refused an insert or updateyour insert/update policy, and whether the user is signed in
data: [], error: nullRLS hid every rowthe select policy, and whether the user is signed in
PGRST116.single() got no row (or more than one)the filter; use .maybeSingle() when “none” is fine
23505a row with this id already existssend it with upsert
PGRST204the table has no column with this namethe spelling of the column
Invalid login credentialswrong email or passwordwhat the user typed; whether the user exists
TypeError: Network request failedthe phone is offlineNetInfo (Part 6)

The dashboard keeps a record of every request in Logs → API Gateway (type rest/v1 in the search to see only your table requests). Each line shows the time, the method and path (for example POST /rest/v1/tasks) and the status code: 200/201 worked, 401 and 403 were refused by Auth or RLS, 400 means the request itself was wrong, 5xx is a problem on the server.

The API Gateway logs of a Supabase project listing GET and POST requests to /rest/v1/tasks from the phone app with status 200 and 201

The phone’s requests: POST (add, 201 Created) and GET (read, 200 OK). Open the logs when the app gets an error you do not understand: the request that failed is there, with its status.

EX 16Read the error, find the fixLoading the exercise…

Checkpoint

Your app signs users in and keeps them signed in, reads and writes their rows, uploads a file, and hears new rows live. Row Level Security — not your app — decides what each user may touch. In the dashboard you can find every table, user, file, policy and request.

Part 6: Local and cloud together: offline basics

21 min

Real apps use both: the phone for speed and for working offline, the cloud for sharing and for keeping data safe when a phone is lost.

cloud-first

Cloud-first

Send to the server, show the result when it answers. Simple, but nothing works without a connection.

local-first

Local-first

Save on the phone and show it at once; send to the server later. Works offline. This part builds a simple version.

The plan for each new or changed task:

  1. Save it in SQLite with a column synced = 0: it is a pending operation, waiting to be sent.
  2. NetInfo tells the app whether the phone is online, and when the connection comes back.
  3. When online: send every row with synced = 0. If the request fails, they stay synced = 0 and are sent next time (a retry).
  4. Only after Supabase answered without an error: synced = 1.
Terminal — install
npx expo install @react-native-community/netinfo
included in Expo Go
import NetInfo from '@react-native-community/netinfo';

const state = await NetInfo.fetch();                 // once: state.isConnected
const unsubscribe = NetInfo.addEventListener((state) => {
  if (state.isConnected) syncPending();              // the connection is back: send what waits
});
// const net = useNetInfo();                         // or as a hook inside a component

Duplicates. Sometimes the server saves the row but its answer never reaches the phone. The phone thinks it failed and sends the task again. With insert, the cloud now has the task twice. The fix: the phone gives each task its own id (Crypto.randomUUID()), and sends with upsert on that id — the second send updates the same row.

On the phone · SQLite

  • No tasks yet.

syncPending()

  1. SELECT … WHERE synced = 0
  2. upsert(rows, { onConflict: 'id' })
  3. UPDATE … SET synced = 1

Waiting.

In the cloud · Supabase tasks

  • No rows yet.

Add a task. Then switch Wi-Fi off, add more, and switch it on again.

sync.tsStep 1 of 4
export async function syncPending() {
  const db = await dbPromise;
  const waiting = await db.getAllAsync('SELECT * FROM tasks WHERE synced = 0');
  if (waiting.length === 0) return 0;
 
  const { error } = await supabase
    .from('tasks')
    .upsert(waiting.map((t) => ({ id: t.id, title: t.title, done: t.done === 1 })), { onConflict: 'id' });
  if (error) throw error;
 
  for (const t of waiting) {
    await db.runAsync('UPDATE tasks SET synced = 1 WHERE id = ?', t.id);
  }
  return waiting.length;
}

Read only the rows that wait: synced = 0. Nothing waiting: stop.

Conflicts. If the same task is changed on two phones while both are offline, the last one to sync wins (the final project keeps an updated_at time for this). Apps that must not lose any change merge them or ask the user — that is a full sync engine, and it is beyond this lab. What you build here is the base those engines start from.

● LIVE DEMONetInfo: is the phone online?Loading the editor and preview…
EX 17The sync steps, in orderLoading the exercise…
EX 18Offline-ready tasksLoading the exercise…

The final project on a real phone. Left: the Wi-Fi is off and a new task waits on the phone. Right: the Wi-Fi is back, the task was sent once, and Supabase has it:

The tasks app on an Android phone in airplane mode: Offline, 1 waiting to sync, the new task marked waiting

Offline: saved on the phone

The same app back online: everything is in the cloud and the task is marked in the cloud

Online again: sent once

Realtime (Part 5 H) does not replace this: it only works while the phone is online. The sync plan is what keeps the app working without a connection.

CheckpointParts 1–6 done

The app works offline: it saves on the phone at once, waits with synced = 0, and sends each task once when the phone is back online.

Part 7: Final project: Offline-Ready Tasks App

No extra time (built in the exercises)

The final project is the exercises put together in one app. Nothing new to learn: open it, read each step, and connect your own Supabase project.

Lab 06 offline-ready tasks app in the Code EditorReact Native · phone emulator · nothing to install · a Guide panel with every step

Requirements

  • A theme setting that survives a restart (AsyncStorage)
  • Tasks saved on the phone at once, with an id made on the phone (SQLite)
  • The session saved encrypted (SecureStore + AsyncStorage: LargeSecureStore)
  • Sign-in, and the tasks in your Supabase project, protected by Row Level Security
  • Offline: tasks wait with synced = 0, are sent when online, once each
offline-tasks
  • App.tsxthe screens: sign in, and the tasks
  • lib/
  • supabase.tsthe client (Part 5) + the encrypted session
  • largeSecureStore.tsSecureStore + AsyncStorage (Part 4)
  • preferences.tsthe theme in AsyncStorage (Part 2)
  • db.tsthe tasks table in SQLite (Part 3)
  • sync.tssyncPending + pullFromCloud (Part 6)
  • supabase/schema.sqlrun once in your project’s SQL Editor
  • .envEXPO_PUBLIC_SUPABASE_URL + _PUBLISHABLE_KEY
Exercise 3

Step 1 · Preference

lib/preferences.ts: the theme with getItem / setItem.

Exercise 6

Step 2 · Tasks on the phone

lib/db.ts: id, title, done, synced, updated_at.

Exercise 8

Step 3 · Encrypted session

lib/largeSecureStore.ts as auth.storage.

Exercise 10

Step 4 · Your project

Run schema.sql, add a user, fill .env.

Exercise 18

Step 5 · Sync

lib/sync.ts: push what waits, then pull the cloud’s tasks.

Test

Step 6 · Airplane mode

Wi-Fi off, add, Wi-Fi on: one row each.

Configuration. In your Supabase project: run supabase/schema.sql in the SQL Editor; add a user in Authentication → Users → Add user (tick Auto Confirm User); copy the Project URL and the publishable key into .env.

On a PC (Expo Go), the same files run in a new project:

Terminal — a new project on your PC
npx create-expo-app@latest offline-tasks --template blank-typescript
cd offline-tasks
npx expo install @supabase/supabase-js react-native-url-polyfill expo-sqlite expo-secure-store expo-crypto @react-native-async-storage/async-storage @react-native-community/netinfo react-native-get-random-values
npm install aes-js
npm install --save-dev @types/aes-js
copy App.tsx, the lib folder and .env from the Code Editor project, then:
npx expo start

Test it (in the Code Editor emulator or on your phone):

  1. Sign in, add two tasks: each shows “in the cloud”, and Table Editor → tasks in Supabase has one row each.
  2. Switch Wi-Fi off (on a phone: airplane mode). Add a task: it shows “waiting”, and nothing reaches Supabase.
  3. Switch Wi-Fi on: it changes to “in the cloud”, still one row each.
  4. Restart the app: still signed in, the theme stayed, the tasks are read from SQLite.
  5. Sign out and sign in again: the tasks come back from the cloud.

CheckpointLab 06

You can choose where every piece of data belongs, and build it: AsyncStorage or MMKV for settings, SQLite for lists, SecureStore for secrets, Supabase for shared data and files — with Row Level Security — and the phone and the cloud working together offline.

Expected result

What you should see

An Offline-Ready Tasks App: a new task is saved on the phone at once (SQLite), the theme is remembered (AsyncStorage), the session is encrypted (SecureStore), and the tasks reach your Supabase project when the phone is online, one row each.

Stuck?

AsyncStorage holds "[object Object]"
Cause

An object was saved without JSON.stringify. AsyncStorage keeps text only.

Fix

Save JSON.stringify(value) and read it back with JSON.parse(text).

"SQLite error: no such table: tasks"
Cause

A query ran before the CREATE TABLE, or the table name is misspelled.

Fix

Run CREATE TABLE IF NOT EXISTS … once when the database opens, and await it before the first query.

"NOT NULL constraint failed" from SQLite
Cause

An INSERT left out a column marked NOT NULL.

Fix

Give that column a value, or a DEFAULT in the CREATE TABLE.

"Invalid key provided to SecureStore"
Cause

The key has a space or another character SecureStore does not allow.

Fix

Keys may contain letters, numbers, ".", "-" and "_" only, for example auth.token.

MMKV: "not supported in Expo Go", or a missing native module
Cause

MMKV is native code that Expo Go does not include.

Fix

Use a development build: npx expo prebuild, then npx expo run:android (or run:ios). Or use AsyncStorage, which works in Expo Go.

Supabase returns an empty list, but the table has rows
Cause

Row Level Security is on and no policy allows this user to read them — or nobody is signed in.

Fix

Sign in first, and add a for select policy (Part 5). With RLS on, no policy means no rows.

"new row violates row-level security policy for table" (code 42501)
Cause

No policy allows this insert or update, or the row would belong to someone else.

Fix

Add a for insert … with check ((select auth.uid()) = user_id) policy, and let the table fill user_id with auth.uid().

"The resource already exists" when uploading
Cause

A file with this path is already in the bucket.

Fix

Add upsert: true to the upload options (and the update and select storage policies), or use a new path.

"Invalid supabaseUrl" or an undefined key
Cause

The .env names do not start with EXPO_PUBLIC_, or Expo was not restarted after editing .env.

Fix

Use EXPO_PUBLIC_SUPABASE_URL and EXPO_PUBLIC_SUPABASE_PUBLISHABLE_KEY, then stop and run npx expo start again.

"Email not confirmed" when signing in
Cause

New Supabase projects ask users to confirm their email first.

Fix

Click the link in the email, or create the user in Authentication → Users → Add user with “Auto Confirm User” ticked.

"Network request failed"
Cause

The phone has no connection (or the emulator’s Wi-Fi is off).

Fix

Expected when offline: the tasks stay synced = 0 and are sent when NetInfo reports the connection is back.

Realtime: the channel says SUBSCRIBED, but no change ever arrives
Cause

The table is not in the supabase_realtime publication, or Row Level Security does not let this user read the row.

Fix

Run alter publication supabase_realtime add table public.tasks; (or Database → Publications), and check the select policy: Realtime only sends rows the user may read.

Realtime: every new task appears two or three times
Cause

A new channel opens each time the screen opens, and the old ones are never removed.

Fix

Return a cleanup from the useEffect: return () => { supabase.removeChannel(channel); };

The user is signed out after every restart
Cause

The client has no auth.storage, or the screen never reads the saved session.

Fix

Give createClient a storage (localStorage from expo-sqlite, or LargeSecureStore) and set the user from onAuthStateChange: it reports the saved session at the start.

Still stuck? Search the troubleshooting center or ask your TA.

End of lab · attendance

Check in for Lab 06

Checking whether check-in is open…