React Native & Firebase: Authentication

faraz amiruddin
Apr 12, 2018 · 6 min read

👋🏽 Hi! I’m Faraz, and I’m a software engineer @ AdHawk. Here’s a quick guide that will get us up and running with Firebase’s Authentication in React Native!

Firebase provides a lot of great products that allow us to develop mobile apps quickly; Realtime Database, Authentication, Cloud Firestore, Cloud Functions, Crashlytics…just to name a few.

We’re going to be building a simple authentication flow using an email and password.

All we need is a way to use the FirebaseSDK with a React Native app…and thanks to the lovely people at Invertase who created react-native-firebase we have just that! It’s an awesome open source project for linking React Native apps with Firebase.


Setting Up Our App

Since we’re starting from scratch, we can go ahead and use the basic starter kit provided by react-native-firebase.

(If you already have an existing application, you can head over to https://rnfirebase.io and follow the manual installation instructions.)

Go ahead and follow their instructions (they’re great) to get our app up and running, and them come back when you’re ready.

Enable Email & Password Authentication in Firebase

After following the instructions linked above, you should be ready to get started.

Here’s a diagram of what we’re going to be building:

A flow diagram of what we’re building

To allow users to use an email and password combo, we need to enable this provider in our firebase console.

To do this, head on over to your Firebase Project → Authentication → Sign-in Method. Click on Email/Password and set to enabled and save. Your dashboard should look like this:

Enabling email and password authentication

Creating our Screens

If we take a look at our diagram, you can see that we have four screens: Loading, SignUp, Login, and Main.

A Loading screen that displays until we determine the auth state of a user, aSignUp screen where the user can create an account, a Login screen where an existing user can login, and a Main screen of our application that we only show to an authenticated user.

We’re going to be using react-navigation for our app’s navigation, so let’s set up our navigator and create our screens.

yarn add react-navigation

Let’s create our screens:

Loading.js

// Loading.jsimport React from 'react'
import { View, Text, ActivityIndicator, StyleSheet } from 'react-native'
export default class Loading extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>Loading</Text>
<ActivityIndicator size="large" />
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}
})

SignUp.js

// SignUp.jsimport React from 'react'
import { StyleSheet, Text, TextInput, View, Button } from 'react-native'
export default class SignUp extends React.Component {
state = { email: '', password: '', errorMessage: null }
handleSignUp = () => {
// TODO: Firebase stuff...
console.log('handleSignUp')
}
render() {
return (
<View style={styles.container}>
<Text>Sign Up</Text>
{this.state.errorMessage &&
<Text style={{ color: 'red' }}>
{this.state.errorMessage}
</Text>}
<TextInput
placeholder="Email"
autoCapitalize="none"
style={styles.textInput}
onChangeText={email => this.setState({ email })}
value={this.state.email}
/>
<TextInput
secureTextEntry
placeholder="Password"
autoCapitalize="none"
style={styles.textInput}
onChangeText={password => this.setState({ password })}
value={this.state.password}
/>
<Button title="Sign Up" onPress={this.handleSignUp} />
<Button
title="Already have an account? Login"
onPress={() => this.props.navigation.navigate('Login')}
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
textInput: {
height: 40,
width: '90%',
borderColor: 'gray',
borderWidth: 1,
marginTop: 8
}
})

Login.js

// Login.jsimport React from 'react'
import { StyleSheet, Text, TextInput, View, Button } from 'react-native'
export default class Login extends React.Component {
state = { email: '', password: '', errorMessage: null }
handleLogin = () => {
// TODO: Firebase stuff...
console.log('handleLogin')
}
render() {
return (
<View style={styles.container}>
<Text>Login</Text>
{this.state.errorMessage &&
<Text style={{ color: 'red' }}>
{this.state.errorMessage}
</Text>}
<TextInput
style={styles.textInput}
autoCapitalize="none"
placeholder="Email"
onChangeText={email => this.setState({ email })}
value={this.state.email}
/>
<TextInput
secureTextEntry
style={styles.textInput}
autoCapitalize="none"
placeholder="Password"
onChangeText={password => this.setState({ password })}
value={this.state.password}
/>
<Button title="Login" onPress={this.handleLogin} />
<Button
title="Don't have an account? Sign Up"
onPress={() => this.props.navigation.navigate('SignUp')}
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
textInput: {
height: 40,
width: '90%',
borderColor: 'gray',
borderWidth: 1,
marginTop: 8
}
})

Main.js

// Main.jsimport React from 'react'
import { StyleSheet, Platform, Image, Text, View } from 'react-native'
export default class Main extends React.Component {
state = { currentUser: null }
render() {
const { currentUser } = this.state
return (
<View style={styles.container}>
<Text>
Hi {currentUser && currentUser.email}!
</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
})

Now that we have all our screens created, let’s wire up our navigation inside our App.js file.

App.js

import React from 'react'
import { StyleSheet, Platform, Image, Text, View } from 'react-native'
import { SwitchNavigator } from 'react-navigation'
// import the different screens
import Loading from './Loading'
import SignUp from './SignUp'
import Login from './Login'
import Main from './Main'
// create our app's navigation stack
const App = SwitchNavigator(
{
Loading,
SignUp,
Login,
Main
},
{
initialRouteName: 'Loading'
}
)
export default App

If we start up our app, you should see our Loading screen with the ActivityIndicator spinning forever. This is what we expected, because we need to determine if the user is authenticated or not to determine where to route them.

If the user is authenticated, route them to the Main screen. Otherwise, send them to the SignUp screen.

Determining if a user is authenticated

We can use Firebase to determine the authentication state of a user. Let’s add a check on our Loading screen that determines if a user is logged in or not.

// Loading.js// Omitted other imports...
import firebase from 'react-native-firebase'
export default class Loading extends React.Component {
componentDidMount() {
firebase.auth().onAuthStateChanged(user => {
this.props.navigation.navigate(user ? 'Main' : 'SignUp')
})
}
// Omitted the rest of the file...

We are using Firebase’s onAuthStateChanged listener to get the current auth state of the user. If they are authenticated, we route them to the Main screen. Otherwise, we send them to the SignUp screen.

Now, since we’re not logged in, you should see the Loading screen for a brief moment, and then be routed to the SignUp screen.

Signing a user up

We need to create a new user, so we can log them in! Let’s head on over to the SignUp screen and wire up our handleSignUp method.

// SignUp.js// Omitted other imports...
import firebase from 'react-native-firebase'
export default class SignUp extends React.Component {
state = { email: '', password: '', errorMessage: null }
handleSignUp = () => {
firebase
.auth()
.createUserWithEmailAndPassword(this.state.email, this.state.password)
.then(() => this.props.navigation.navigate('Main'))
.catch(error => this.setState({ errorMessage: error.message }))
}
// Omitted the rest of the file...

When a user submits the form, we createUserWithEmailAndPassword and then navigate them to the Main screen. If there is an error we catch it and display it.

Displaying the current user on the Main screen

With our current implementation, we will only see the Main screen if a user is logged in. We need to grab the currentUser from firebase so that we can display their email. Let’s update our Main screen do handle this.

// Main.js// Omitted other imports...
import firebase from 'react-native-firebase'
export default class Main extends React.Component {
state = { currentUser: null }
componentDidMount() {
const { currentUser } = firebase.auth()
this.setState({ currentUser })
}
// Omitted the rest of the file...

Now, when we see the Main screen, we should see the user’s email address. If we refresh the app, we should be automatically routed to the Main screen because are already authenticated.

The last step is that we should be able to log in a user after we have already created an account!

Logging an already existing user in

Home stretch! Let’s update our Login screen so that we can login with an existing account.

// Login.js// Omitted other imports...
import firebase from 'react-native-firebase'
export default class Login extends React.Component {
state = { email: '', password: '', errorMessage: null }
handleLogin = () => {
const { email, pasword } = this.state
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then(() => this.props.navigation.navigate('Main'))
.catch(error => this.setState({ errorMessage: error.message }))
}
// Omitted the rest of the file...

Sweet!

We now have a simple authentication flow set up with React Native & Firebase. If you would like access to the entire source code, I’ve uploaded it here: https://github.com/faahmad/react-native-firebase-auth

Thanks for reading!


Hey! I’m Faraz.

I’m a software engineer and co-founder @ SHOgigs.

I write about what interests me, which currently includes react, react native, javascript, basketball, life, film, and basketball.

If you liked this article, please recommend and share it!

React Native Training

Stories and tutorials for developers interested in React Native

faraz amiruddin

Written by

software engineer @ AdHawk — my musings

React Native Training

Stories and tutorials for developers interested in React Native

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade