top of page

User authentication with Firebase for React

One of the first things any web app developer needs to do after building their React app is implement user authentication. A smooth, secure user authentication process is key to on-boarding and retaining users. The Firebase platform, made by Google, offers countless tools that make web app development easier (including user authentication support).


Follow the steps below to add user authentication with Firebase to your React app! If you get stuck or need extra help, schedule an intro call with CodeConda for free.


1. Create a Firebase Project

  • Go to the Firebase Console and create a new project if you haven't already.

  • In the project dashboard, navigate to the "Authentication" section in the left sidebar.


2. Set Up Firebase Configuration

  • Click on the "Web" icon (</>) to add a web app to your project.

  • Register the app, and Firebase will provide you with a configuration object containing API keys and other credentials. Keep this configuration handy, as you'll need it in your React app.


3. Initialize Firebase in Your React App

  • In your React project, install the Firebase SDK by running `npm install firebase`.

  • Create a new file (e.g., `firebase.js`) to initialize Firebase with the configuration you obtained earlier:

     import firebase from 'firebase/app';
     import 'firebase/auth';
     
     const firebaseConfig = {
       apiKey: 'YOUR_API_KEY',
       authDomain: 'YOUR_AUTH_DOMAIN',
       projectId: 'YOUR_PROJECT_ID',
       storageBucket: 'YOUR_STORAGE_BUCKET',
       messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
       appId: 'YOUR_APP_ID'
     };
     
     // Initialize Firebase
     firebase.initializeApp(firebaseConfig);
     
     export default firebase;

4. Implement User Registration

  • Create a registration form in your React component.

  • Use Firebase's `createUserWithEmailAndPassword` method to register a new user:

     import React, { useState } from 'react';
     import firebase from './firebase';
     
     const Registration = () => {
       const [email, setEmail] = useState('');
       const [password, setPassword] = useState('');
       
       const handleRegistration = async () => {
         try {
           await firebase.auth().createUserWithEmailAndPassword(email, password);
           // User registered successfully
         } catch (error) {
           console.error('Registration Error:', error);
         }
       };
       
       return (
         <div>
           <input type="email" value={email} onChange={e => setEmail(e.target.value)} />
           <input type="password" value={password} onChange={e => setPassword(e.target.value)} />
           <button onClick={handleRegistration}>Register</button>
         </div>
       );
     };
     
     export default Registration;

5. Implement User Login

  • Create a login form in your React component.

  • Use Firebase's `signInWithEmailAndPassword` method to authenticate a user:

     import React, { useState } from 'react';
     import firebase from './firebase';
     
     const Login = () => {
       const [email, setEmail] = useState('');
       const [password, setPassword] = useState('');
       
       const handleLogin = async () => {
         try {
           await firebase.auth().signInWithEmailAndPassword(email, password);
           // User logged in successfully
         } catch (error) {
           console.error('Login Error:', error);
         }
       };
       
       return (
         <div>
           <input type="email" value={email} onChange={e => setEmail(e.target.value)} />
           <input type="password" value={password} onChange={e => setPassword(e.target.value)} />
           <button onClick={handleLogin}>Login</button>
         </div>
       );
     };
     
     export default Login;

6. Implement Logout

  • To log the user out, use Firebase's `signOut` method:

     import React from 'react';
     import firebase from './firebase';
     
     const Logout = () => {
       const handleLogout = async () => {
         try {
           await firebase.auth().signOut();
           // User logged out successfully
         } catch (error) {
           console.error('Logout Error:', error);
         }
       };
       
       return (
         <div>
           <button onClick={handleLogout}>Logout</button>
         </div>
       );
     };
     
     export default Logout;

7. Check Authentication State

  • Firebase provides an `onAuthStateChanged` listener that you can use to keep track of the user's authentication state:

     import React, { useState, useEffect } from 'react';
     import firebase from './firebase';
     
     const AuthStatus = () => {
       const [user, setUser] = useState(null);
       
       useEffect(() => {
         const unsubscribe = firebase.auth().onAuthStateChanged(authUser => {
           if (authUser) {
             // User is signed in
             setUser(authUser);
           } else {
             // User is signed out
             setUser(null);
           }
         });
         
         return () => unsubscribe();
       }, []);
       
       return (
         <div>
           {user ? <p>Welcome, {user.email}!</p> : <p>Please log in.</p>}
         </div>
       );
     };
     
     export default AuthStatus;

8. Routing and Integration

  • Integrate the above components into your app's routing structure.

  • You can use libraries like `react-router-dom` to handle different routes for registration, login, and other parts of your app.


9. Styling and User Feedback

  • Design your forms, buttons, and messages for a user-friendly experience.

  • Provide appropriate feedback for successful and failed operations.

10. React User Authentication: Complete!

  • Remember that this is a basic implementation, and you can enhance it further by adding features like password reset, social media authentication, user profile management, and more. Always prioritize security and follow best practices when handling user authentication in your React app.

Comments


bottom of page