Short-Video App with React Native and Supabase · Course book
Chapter 7: Accounts, Sessions and the Auth Provider
Nearly every feature of a social app depends on knowing who the user is: whose video this is, who liked it, who may read a chat. Authentication answers that question, and doing it well means more than a login form. Passwords must be stored safely, sessions must survive the app being closed, every screen needs access to the current user without repeated network calls, and the app must send signed-out users to the login screen and signed-in users to the feed. This chapter explains how authentication is built with Supabase in a React Native app: the sign-up and login screens, creating a profile row in the app's own users table, an auth provider that shares the user across the app, sessions and redirects, and password strength, worked out by hand.
Sign-up and login screens
The two screens share a design: the app's logo, a few text inputs, a primary button and a link to the other screen. Login needs an email and a password; sign-up also asks for a username, which will be shown on videos and comments. Each input is a controlled TextInput whose value lives in state. A few properties make them pleasant to use on a phone: keyboardType="email-address" shows the @ key, autoCapitalize="none" stops the keyboard capitalising the first letter of an email, secureTextEntry hides the password, and the textContentType or autoComplete properties let the phone's password manager fill in saved details.
Before sending anything, the screen validates what it can: the email looks like an email, the password meets the minimum length and the username is not empty and uses allowed characters. Showing errors next to the field that caused them, rather than in a generic alert, helps users fix them quickly. While a request is in progress, the button shows a spinner and is disabled, so a double tap does not create two requests.
Error messages after a failed login deserve thought. Saying "No account with this email" reveals which emails are registered, which helps anyone trying to guess accounts; a neutral "Email or password is incorrect" is safer and just as useful to a genuine user. Sign-up is the exception, because a user must be told that a username is taken in order to choose another. Two more flows complete a real authentication system: email confirmation, where the user clicks a link before the account becomes active, which proves they own the address, and password reset, where a link sent by email lets them choose a new password. Supabase provides both, and on a phone they rely on deep links, addresses that open the app at a particular screen, configured in the app's scheme settings and in the Supabase dashboard's list of allowed redirect addresses.
Supabase Auth and the users table
Supabase Authentication manages the accounts themselves. supabase.auth.signUp({ email, password }) creates an account, supabase.auth.signInWithPassword({ email, password }) signs in and supabase.auth.signOut() signs out. Supabase stores the password only as a salted hash, using a slow hashing algorithm designed to resist guessing, so even someone who obtained the database could not read passwords. Depending on the project's settings, new users may need to confirm their email before signing in.
Supabase keeps accounts in its own internal schema, which the app cannot extend directly. The app's profile information, such as the username and profile photo, belongs in the User table created with Prisma. The two are linked by using the same id: after a successful sign-up, the app inserts a row into the User table with the new account's id, the username and the email.
async function signUp(email, password, username) {
const { data, error } = await supabase.auth.signUp({ email, password });
if (error) throw error;
const { error: profileError } = await supabase
.from("User")
.insert({ id: data.user.id, username, email });
if (profileError) throw profileError;
return data.user;
}
This two-step approach has a gap: if the app closes between the two steps, an account exists without a profile row. A more robust alternative is a database trigger that creates the profile automatically whenever a new account is inserted, passing the username through the sign-up call's metadata. Either way, a row level security policy should allow users to insert and update only the profile row whose id matches their own, using auth.uid().
| Action | Supabase call | Then the app |
|---|---|---|
| Sign up | auth.signUp | Creates the User row, stores the user, opens the feed |
| Log in | auth.signInWithPassword | Loads the User row, stores the user, opens the feed |
| App start | auth.getSession | Restores the saved session, if any, then loads the User row |
| Log out | auth.signOut | Clears the stored user, returns to login |
An auth provider for the whole app
Many screens need the current user: the feed to show the right buttons, the camera to upload into the right folder, the profile to show the right page. Fetching the user on every screen would waste requests and cause flickering. Instead, an auth provider built with React context loads the user once and shares it.
The provider is a component that wraps the whole app in the root layout. It holds the current user in state, exposes functions for signing in, signing up and signing out, and offers a useAuth hook that any screen can call to read them. When the provider starts, it asks Supabase for the saved session; if there is one, it fetches the matching User row and stores it. It also subscribes to supabase.auth.onAuthStateChange, which reports sign-ins, sign-outs and token refreshes, so that the stored user stays correct. The subscription is created once, when the provider mounts, and removed when it unmounts, to avoid duplicate listeners. Because the full User row, with the username and photo, is stored in the provider, every screen can display it without a further request.
Redirects follow from the provider's state. The root layout reads the user: while the session is still loading it shows a splash or loading screen; if there is no user, it redirects to the login screen; if there is one, it shows the tabs. After a successful sign-in, router.replace moves to the tabs so that the back button cannot return to the login form, and after sign-out the same logic sends the user back.
Sessions that survive restarts
A session consists of a short-lived access token, sent with every request to prove who the user is, and a longer-lived refresh token, used to obtain new access tokens before they expire. Keeping access tokens short-lived, often an hour, limits the damage if one is ever exposed, because it soon stops working. The Supabase client, configured with AsyncStorage as in the earlier setup, saves the session on the phone and refreshes it automatically while the app is running, so users stay signed in for weeks without retyping their password.
One detail matters on mobile: timers do not run reliably while an app is in the background. Supabase's recommended setup listens for the app returning to the foreground and restarts automatic refreshing then, stopping it when the app goes into the background. Without this, a user who reopens the app after a long break might briefly see failed requests until the token is refreshed.
How strong is a password?
A password's strength against guessing can be measured as entropy in bits: if each character is chosen at random from a set of c characters, each adds log2 c bits, and a password of length L has L × log2 c bits. Each extra bit doubles the number of guesses an attacker needs.
These figures assume random passwords; human-chosen ones are far weaker, because people pick words and patterns. Sensible rules are therefore a reasonable minimum length, encouragement to use a password manager, and checks against lists of commonly used passwords, rather than demands for special symbols that make passwords harder to remember without making them much stronger. A long passphrase of several random words is both strong and memorable.
Practice tasks
- Compute the entropy of a 10-character password chosen randomly from 36 characters, the lower-case letters and digits.
- How many more bits does a 16-character lower-case password have than an 8-character one?
- Describe what can go wrong if the app crashes between creating the account and inserting the User row, and how a trigger avoids it.
- Write the steps the auth provider takes when the app starts.
- Why does the app use
router.replacerather thanrouter.pushafter signing in? - Explain the roles of the access token and the refresh token.
This course book is available to read online only at tech-academy.chrysolites.org.