Use Supabase Auth with React Native
Learn how to use Supabase Auth with React Native
Create a new Supabase project
Launch a new project in the Supabase Dashboard.
Your new database has a table for storing your users. You can see that this table is currently empty by running some SQL in the SQL Editor.
SQL_EDITOR
1select * from auth.users;Create a React app
Create a React app using the create-expo-app command.
Terminal
1npx create-expo-app -t expo-template-blank-typescript my-appInstall the Supabase client library
Install supabase-js and the required dependencies.
Terminal
1cd my-app && npx expo install @supabase/supabase-js @react-native-async-storage/async-storage @rneui/themed react-native-url-polyfillSet up your login component
Create a helper file lib/supabase.ts that exports a Supabase client using your Project URL and key.
Project URL
Publishable key
Anon key
lib/supabase.ts
1import { AppState, Platform } from 'react-native'2import 'react-native-url-polyfill/auto'3import AsyncStorage from '@react-native-async-storage/async-storage'4import { createClient, processLock } from '@supabase/supabase-js'56const supabaseUrl = YOUR_REACT_NATIVE_SUPABASE_URL7const supabaseAnonKey = YOUR_REACT_NATIVE_SUPABASE_PUBLISHABLE_KEY89export const supabase = createClient(supabaseUrl, supabaseAnonKey, {10 auth: {11 ...(Platform.OS !== "web" ? { storage: AsyncStorage } : {}),12 autoRefreshToken: true,13 persistSession: true,14 detectSessionInUrl: false,15 lock: processLock,16 },17})1819// Tells Supabase Auth to continuously refresh the session automatically20// if the app is in the foreground. When this is added, you will continue21// to receive `onAuthStateChange` events with the `TOKEN_REFRESHED` or22// `SIGNED_OUT` event if the user's session is terminated. This should23// only be registered once.24if (Platform.OS !== "web") {25 AppState.addEventListener('change', (state) => {26 if (state === 'active') {27 supabase.auth.startAutoRefresh()28 } else {29 supabase.auth.stopAutoRefresh()30 }31 })32}You can also get the Project URL and key from the project's Connect dialog.
Changes to API keys
Supabase is changing the way keys work to improve project security and developer experience. You can read the full announcement, but in the transition period, you can use both the current anon and service_role keys and the new publishable key with the form sb_publishable_xxx which will replace the older keys.
In most cases, you can get the correct key from the Project's Connect dialog, but if you want a specific key, you can find all keys in the API Keys section of a Project's Settings page:
- For legacy keys, copy the
anonkey for client-side operations and theservice_rolekey for server-side operations from the Legacy API Keys tab. - For new keys, open the API Keys tab, if you don't have a publishable key already, click Create new API Keys, and copy the value from the Publishable key section.
Read the API keys docs for a full explanation of all key types and their uses.
Create a login component
Let's set up a React Native component to manage logins and sign ups.
components/Auth.tsx
1import React, { useState } from 'react'2import { Alert, StyleSheet, View } from 'react-native'3import { supabase } from '../lib/supabase'4import { Button, Input } from '@rneui/themed'56export default function Auth() {7 const [email, setEmail] = useState('')8 const [password, setPassword] = useState('')9 const [loading, setLoading] = useState(false)1011 async function signInWithEmail() {12 setLoading(true)13 const { error } = await supabase.auth.signInWithPassword({14 email: email,15 password: password,16 })1718 if (error) Alert.alert(error.message)19 setLoading(false)20 }2122 async function signUpWithEmail() {23 setLoading(true)24 const {25 data: { session },26 error,27 } = await supabase.auth.signUp({28 email: email,29 password: password,30 })3132 if (error) Alert.alert(error.message)33 if (!session) Alert.alert('Please check your inbox for email verification!')34 setLoading(false)35 }3637 return (38 <View style={styles.container}>39 <View style={[styles.verticallySpaced, styles.mt20]}>40 <Input41 label="Email"42 leftIcon={{ type: 'font-awesome', name: 'envelope' }}43 onChangeText={(text) => setEmail(text)}44 value={email}45 placeholder="email@address.com"46 autoCapitalize={'none'}47 />48 </View>49 <View style={styles.verticallySpaced}>50 <Input51 label="Password"52 leftIcon={{ type: 'font-awesome', name: 'lock' }}53 onChangeText={(text) => setPassword(text)}54 value={password}55 secureTextEntry={true}56 placeholder="Password"57 autoCapitalize={'none'}58 />59 </View>60 <View style={[styles.verticallySpaced, styles.mt20]}>61 <Button title="Sign in" disabled={loading} onPress={() => signInWithEmail()} />62 </View>63 <View style={styles.verticallySpaced}>64 <Button title="Sign up" disabled={loading} onPress={() => signUpWithEmail()} />65 </View>66 </View>67 )68}6970const styles = StyleSheet.create({71 container: {72 marginTop: 40,73 padding: 12,74 },75 verticallySpaced: {76 paddingTop: 4,77 paddingBottom: 4,78 alignSelf: 'stretch',79 },80 mt20: {81 marginTop: 20,82 },83})Add the Auth component to your app
Add the Auth component to your App.tsx file. If the user is logged in, print the user id to the screen.
App.tsx
1import 'react-native-url-polyfill/auto'2import { useState, useEffect } from 'react'3import { supabase } from './lib/supabase'4import Auth from './components/Auth'5import { View, Text } from 'react-native'6import { Session } from '@supabase/supabase-js'78export default function App() {9 const [session, setSession] = useState<Session | null>(null)1011 useEffect(() => {12 supabase.auth.getSession().then(({ data: { session } }) => {13 setSession(session)14 })1516 supabase.auth.onAuthStateChange((_event, session) => {17 setSession(session)18 })19 }, [])2021 return (22 <View>23 <Auth />24 {session && session.user && <Text>{session.user.id}</Text>}25 </View>26 )27}Start the app
Start the app, and follow the instructions in the terminal.
Terminal
1npm start