How to Use Firebase for Authentication and Database in React

How to Use Firebase for Authentication and Database in React

Firebase is a powerful platform by Google that provides backend services like authentication, real-time databases, and hosting. It's incredibly useful for developers who want to quickly build and scale web applications without managing servers themselves. In this guide, we'll walk through how to integrate Firebase for authentication and real-time database functionality in a React application.


What is Firebase?

Firebase offers a suite of tools that can help developers build web and mobile applications without worrying about infrastructure. It provides a variety of services, including:

  • Firebase Authentication: A service to authenticate users using email/password, Google, Facebook, Twitter, and other social media accounts.

  • Firebase Realtime Database: A NoSQL cloud database that supports real-time data synchronization.

  • Firebase Firestore: A more advanced and scalable database that works similarly to Realtime Database but with additional features.

  • Firebase Hosting: A fast and secure hosting service for web apps.


Setting Up Firebase in Your React Project

Step 1: Create a Firebase Project

Before you can start using Firebase, you need to create a Firebase project:

  1. Go to Firebase Console.

  2. Click on Add Project and follow the instructions to create a new project.

  3. Once your project is created, you'll be directed to the project dashboard.

Step 2: Install Firebase SDK

In your React project, install the Firebase SDK by running the following command:

npm install firebase

Step 3: Initialize Firebase in Your App

Create a firebase.js file in your project’s src folder to initialize Firebase with the configuration details from your Firebase console.

Go to the Firebase console, click on the settings gear icon, and select Project settings. Under Your apps, click on Web to get your Firebase config.

// src/firebase.js
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getDatabase } from "firebase/database";

// Your Firebase configuration from the console
const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  databaseURL: "YOUR_DATABASE_URL",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID",
};

const app = initializeApp(firebaseConfig);

const auth = getAuth(app);
const database = getDatabase(app);

export { auth, database };

Firebase Authentication in React

Firebase Authentication simplifies the process of adding user sign-in functionality. We'll walk through how to use Firebase Authentication with email/password authentication.

Step 1: Create a Sign-Up and Login Form

Let’s start by creating components for user sign-up and login.

// SignUp.js
import React, { useState } from "react";
import { createUserWithEmailAndPassword } from "firebase/auth";
import { auth } from "./firebase";

const SignUp = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");

  const handleSignUp = async (e) => {
    e.preventDefault();

    try {
      await createUserWithEmailAndPassword(auth, email, password);
      setEmail("");
      setPassword("");
    } catch (err) {
      setError(err.message);
    }
  };

  return (
    <div>
      <h2>Sign Up</h2>
      {error && <p>{error}</p>}
      <form onSubmit={handleSignUp}>
        <input
          type="email"
          placeholder="Email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />
        <input
          type="password"
          placeholder="Password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        <button type="submit">Sign Up</button>
      </form>
    </div>
  );
};

export default SignUp;
// Login.js
import React, { useState } from "react";
import { signInWithEmailAndPassword } from "firebase/auth";
import { auth } from "./firebase";

const Login = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");

  const handleLogin = async (e) => {
    e.preventDefault();

    try {
      await signInWithEmailAndPassword(auth, email, password);
      setEmail("");
      setPassword("");
    } catch (err) {
      setError(err.message);
    }
  };

  return (
    <div>
      <h2>Login</h2>
      {error && <p>{error}</p>}
      <form onSubmit={handleLogin}>
        <input
          type="email"
          placeholder="Email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />
        <input
          type="password"
          placeholder="Password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        <button type="submit">Login</button>
      </form>
    </div>
  );
};

export default Login;

Step 2: Handle User State

You may want to keep track of whether a user is signed in or not. To do this, use onAuthStateChanged:

// App.js
import React, { useState, useEffect } from "react";
import { onAuthStateChanged } from "firebase/auth";
import { auth } from "./firebase";
import SignUp from "./SignUp";
import Login from "./Login";

const App = () => {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, setUser);
    return () => unsubscribe();
  }, []);

  return (
    <div>
      {user ? (
        <div>
          <h2>Welcome {user.email}</h2>
          <button onClick={() => auth.signOut()}>Sign Out</button>
        </div>
      ) : (
        <div>
          <SignUp />
          <Login />
        </div>
      )}
    </div>
  );
};

export default App;

Using Firebase Realtime Database in React

Firebase provides a real-time NoSQL database that allows you to sync data instantly across all clients.

Step 1: Set Up Realtime Database

In the Firebase console, navigate to Database and choose Realtime Database. Create a database and set up your rules to allow reading and writing data.

Example rules:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

Step 2: Write Data to the Database

We can write data to Firebase using the set method:

// Write data to Firebase
import { ref, set } from "firebase/database";
import { database } from "./firebase";

const writeUserData = (userId, name, email) => {
  set(ref(database, "users/" + userId), {
    username: name,
    email: email,
  });
};

Step 3: Read Data from the Database

To read data, we use the onValue method to listen for changes in real-time.

// Read data from Firebase
import { ref, onValue } from "firebase/database";
import { database } from "./firebase";

const readUserData = () => {
  const userRef = ref(database, "users/1");
  onValue(userRef, (snapshot) => {
    const data = snapshot.val();
    console.log(data);
  });
};

Conclusion

Firebase makes it incredibly easy to implement user authentication and manage data in a real-time database in React applications. In this guide, we covered how to set up Firebase Authentication and use Firebase Realtime Database in your React app. By leveraging Firebase's powerful tools, you can focus on building your app's features rather than worrying about backend infrastructure.

Start experimenting with Firebase in your React applications, and you’ll quickly see how it can simplify your development process.