0
0
FirebaseHow-ToBeginner · 4 min read

How to Use Firebase Auth with React: Simple Guide

To use Firebase Auth with React, first install Firebase and initialize it with your project config. Then use Firebase Auth methods like signInWithEmailAndPassword inside React components to handle user login and state.
📐

Syntax

First, import Firebase and initialize it with your project settings. Then use the getAuth function to get the authentication service. Use methods like signInWithEmailAndPassword(auth, email, password) to sign in users.

Example parts:

  • initializeApp(config): sets up Firebase with your project info.
  • getAuth(): gets the auth service.
  • signInWithEmailAndPassword(auth, email, password): signs in a user.
javascript
import { initializeApp } from 'firebase/app';
import { getAuth, signInWithEmailAndPassword } from 'firebase/auth';

const firebaseConfig = {
  apiKey: 'YOUR_API_KEY',
  authDomain: 'YOUR_AUTH_DOMAIN',
  projectId: 'YOUR_PROJECT_ID',
  // other config
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

// Sign in user
signInWithEmailAndPassword(auth, 'user@example.com', 'password123')
  .then(userCredential => {
    const user = userCredential.user;
    console.log('Signed in:', user.email);
  })
  .catch(error => {
    console.error('Error signing in:', error.message);
  });
Output
Signed in: user@example.com
💻

Example

This React example shows how to create a simple login form that uses Firebase Auth to sign in users with email and password. It handles user input, calls Firebase sign-in, and shows success or error messages.

javascript
import React, { useState } from 'react';
import { initializeApp } from 'firebase/app';
import { getAuth, signInWithEmailAndPassword } from 'firebase/auth';

const firebaseConfig = {
  apiKey: 'YOUR_API_KEY',
  authDomain: 'YOUR_AUTH_DOMAIN',
  projectId: 'YOUR_PROJECT_ID',
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

function Login() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [message, setMessage] = useState('');

  const handleLogin = (e) => {
    e.preventDefault();
    signInWithEmailAndPassword(auth, email, password)
      .then(userCredential => {
        setMessage(`Welcome, ${userCredential.user.email}`);
      })
      .catch(error => {
        setMessage(`Login failed: ${error.message}`);
      });
  };

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

export default Login;
Output
When user enters valid email and password and clicks Sign In, message shows: "Welcome, user@example.com" or error message if failed.
⚠️

Common Pitfalls

Common mistakes include:

  • Not initializing Firebase before using auth methods.
  • Using wrong or missing Firebase config values.
  • Not handling promises from sign-in methods properly.
  • Forgetting to secure API keys and not restricting them in Firebase console.
  • Not updating React state correctly after sign-in.

Always check errors and show user-friendly messages.

javascript
/* Wrong: Using auth before initializing Firebase */
import { getAuth, signInWithEmailAndPassword } from 'firebase/auth';

const auth = getAuth(); // No app initialized yet

signInWithEmailAndPassword(auth, 'email', 'pass'); // Error

/* Right: Initialize app first */
import { initializeApp } from 'firebase/app';

const firebaseConfig = {
  apiKey: 'YOUR_API_KEY',
  authDomain: 'YOUR_AUTH_DOMAIN',
  projectId: 'YOUR_PROJECT_ID',
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

signInWithEmailAndPassword(auth, 'email', 'pass'); // Works
📊

Quick Reference

Key Firebase Auth methods for React:

  • initializeApp(config): Setup Firebase.
  • getAuth(app): Get auth service.
  • signInWithEmailAndPassword(auth, email, password): Sign in user.
  • createUserWithEmailAndPassword(auth, email, password): Register user.
  • signOut(auth): Log out user.

Remember to handle promises and update React state accordingly.

Key Takeaways

Initialize Firebase app before using authentication methods.
Use getAuth(app) to get the auth service for your React app.
Handle sign-in promises with then/catch to update UI.
Secure your Firebase config and restrict API keys in the console.
Update React state to reflect user login status and errors.