Auth

Use Supabase Auth with React Native

Learn how to use Supabase Auth with React Native


1

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
1
select * from auth.users;
2

Create a React app

Create a React app using the create-expo-app command.

Terminal
1
npx create-expo-app -t expo-template-blank-typescript my-app
3

Install the Supabase client library

Install supabase-js and the required dependencies.

Terminal
1
cd my-app && npx expo install @supabase/supabase-js @react-native-async-storage/async-storage @rneui/themed react-native-url-polyfill
4

Set 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
1
import { AppState, Platform } from 'react-native'
2
import 'react-native-url-polyfill/auto'
3
import AsyncStorage from '@react-native-async-storage/async-storage'
4
import { createClient, processLock } from '@supabase/supabase-js'
5
6
const supabaseUrl = YOUR_REACT_NATIVE_SUPABASE_URL
7
const supabaseAnonKey = YOUR_REACT_NATIVE_SUPABASE_PUBLISHABLE_KEY
8
9
export 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
})
18
19
// Tells Supabase Auth to continuously refresh the session automatically
20
// if the app is in the foreground. When this is added, you will continue
21
// to receive `onAuthStateChange` events with the `TOKEN_REFRESHED` or
22
// `SIGNED_OUT` event if the user's session is terminated. This should
23
// only be registered once.
24
if (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.

Read the API keys docs for a full explanation of all key types and their uses.

5

Create a login component

Let's set up a React Native component to manage logins and sign ups.

components/Auth.tsx
1
import React, { useState } from 'react'
2
import { Alert, StyleSheet, View } from 'react-native'
3
import { supabase } from '../lib/supabase'
4
import { Button, Input } from '@rneui/themed'
5
6
export default function Auth() {
7
const [email, setEmail] = useState('')
8
const [password, setPassword] = useState('')
9
const [loading, setLoading] = useState(false)
10
11
async function signInWithEmail() {
12
setLoading(true)
13
const { error } = await supabase.auth.signInWithPassword({
14
email: email,
15
password: password,
16
})
17
18
if (error) Alert.alert(error.message)
19
setLoading(false)
20
}
21
22
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
})
31
32
if (error) Alert.alert(error.message)
33
if (!session) Alert.alert('Please check your inbox for email verification!')
34
setLoading(false)
35
}
36
37
return (
38
<View style={styles.container}>
39
<View style={[styles.verticallySpaced, styles.mt20]}>
40
<Input
41
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
<Input
51
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
}
69
70
const 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
})
6

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
1
import 'react-native-url-polyfill/auto'
2
import { useState, useEffect } from 'react'
3
import { supabase } from './lib/supabase'
4
import Auth from './components/Auth'
5
import { View, Text } from 'react-native'
6
import { Session } from '@supabase/supabase-js'
7
8
export default function App() {
9
const [session, setSession] = useState<Session | null>(null)
10
11
useEffect(() => {
12
supabase.auth.getSession().then(({ data: { session } }) => {
13
setSession(session)
14
})
15
16
supabase.auth.onAuthStateChange((_event, session) => {
17
setSession(session)
18
})
19
}, [])
20
21
return (
22
<View>
23
<Auth />
24
{session && session.user && <Text>{session.user.id}</Text>}
25
</View>
26
)
27
}
7

Start the app

Start the app, and follow the instructions in the terminal.

Terminal
1
npm start