# How to Fix Firebase Authentication Not Working

- Tool: Firebase
- Difficulty: Beginner
- Time required: 10-15 min
- Compatibility: Firebase (Spark and Blaze plans), firebase v9+ modular SDK
- Last updated: March 2026

## TL;DR

When Firebase authentication is not working, systematically check these common causes: the sign-in provider is not enabled in the Firebase Console, your API key is restricted or incorrect, the authorized domains list is missing your domain, onAuthStateChanged is not being used to wait for auth initialization, or your Firebase config object has incorrect values. This tutorial provides a step-by-step debugging checklist that resolves the most frequent Firebase Auth failures.

## Debugging Firebase Authentication When It Stops Working

Firebase Auth failures can stem from configuration issues, timing bugs, or provider misconfigurations. This tutorial walks through a systematic debugging checklist covering every common cause of auth failures, from incorrect config objects to race conditions with onAuthStateChanged. Each step includes the exact error message you might see and how to resolve it.

## Before you start

- A Firebase project with Authentication set up
- The firebase npm package installed (v9 or later)
- Access to the Firebase Console for your project
- Your app's Firebase config object

## Step-by-step guide

### 1. Verify the sign-in provider is enabled in the Console

The most common reason authentication fails is that the sign-in method is not enabled. Go to Firebase Console > Authentication > Sign-in method and confirm the provider you are using (Email/Password, Google, GitHub, etc.) shows as 'Enabled'. If you are using OAuth providers like Google or GitHub, you also need to configure the client ID and secret from the provider's developer console. Without enabling the provider, Firebase returns auth/operation-not-allowed.

```
// This error means the provider is not enabled:
// FirebaseError: Firebase: Error (auth/operation-not-allowed)

// Fix: Go to Firebase Console > Authentication > Sign-in method
// Click the provider and toggle 'Enable' to on
```

**Expected result:** The sign-in provider shows as Enabled in the Firebase Console Sign-in method tab.

### 2. Check your Firebase config object for errors

A wrong or incomplete config object silently breaks authentication. Go to Firebase Console > Project Settings (gear icon) > General > Your apps and copy the exact config. Compare it with the config in your code. The most common mistakes are using the config from a different project, missing the authDomain field, or having a typo in the apiKey. Every field must match exactly.

```
import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'

// Copy this exactly from Firebase Console > Project Settings
const firebaseConfig = {
  apiKey: 'AIzaSy...',           // Must match your project
  authDomain: 'your-project.firebaseapp.com',
  projectId: 'your-project',
  storageBucket: 'your-project.appspot.com',
  messagingSenderId: '123456789',
  appId: '1:123456789:web:abc123'
}

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

**Expected result:** Firebase initializes without errors and getAuth() returns a valid Auth instance.

### 3. Add your domain to the authorized domains list

Firebase Auth only works on domains listed in the authorized domains. Go to Firebase Console > Authentication > Settings > Authorized domains. Localhost is included by default for development. For production, add your custom domain. If you are testing from a non-standard port or a deployed URL that is not listed, auth operations will fail with auth/unauthorized-domain.

```
// This error means your domain is not authorized:
// FirebaseError: Firebase: Error (auth/unauthorized-domain)

// Fix: Firebase Console > Authentication > Settings > Authorized domains
// Add: your-app.vercel.app (or your custom domain)
```

**Expected result:** Your app's domain appears in the authorized domains list and auth operations work from that domain.

### 4. Wait for auth initialization with onAuthStateChanged

Firebase Auth loads asynchronously. If you check currentUser immediately after page load, it may be null even if the user is signed in. The auth state needs time to initialize from the persisted session. Always use onAuthStateChanged to wait for the auth state to resolve before making decisions about whether the user is logged in.

```
import { getAuth, onAuthStateChanged } from 'firebase/auth'

const auth = getAuth()

// WRONG: currentUser may be null during initialization
console.log(auth.currentUser) // Often null on page load

// CORRECT: Wait for auth state to initialize
onAuthStateChanged(auth, (user) => {
  if (user) {
    console.log('User is signed in:', user.uid)
  } else {
    console.log('User is signed out')
  }
})
```

**Expected result:** The auth state is correctly detected after initialization, and signed-in users are recognized.

### 5. Check the browser console for specific error codes

Firebase Auth provides specific error codes that tell you exactly what went wrong. Catch errors from auth operations and log the error.code property. Common codes include auth/wrong-password, auth/user-not-found, auth/too-many-requests, auth/network-request-failed, and auth/popup-closed-by-user. Each code has a specific fix.

```
import { signInWithEmailAndPassword } from 'firebase/auth'

try {
  await signInWithEmailAndPassword(auth, email, password)
} catch (error: any) {
  switch (error.code) {
    case 'auth/user-not-found':
      console.log('No account exists with this email')
      break
    case 'auth/wrong-password':
      console.log('Incorrect password')
      break
    case 'auth/too-many-requests':
      console.log('Too many failed attempts. Try again later.')
      break
    case 'auth/network-request-failed':
      console.log('Network error. Check your connection.')
      break
    case 'auth/invalid-credential':
      console.log('Email or password is incorrect')
      break
    default:
      console.log('Auth error:', error.code, error.message)
  }
}
```

**Expected result:** Error codes are caught and displayed, pointing to the specific cause of the auth failure.

### 6. Verify API key restrictions are not blocking auth

If you restricted your API key in the Google Cloud Console, authentication may fail silently. Go to Google Cloud Console > APIs & Services > Credentials, find your Firebase API key, and check the restrictions. For Firebase Auth to work, the key must have access to the Identity Toolkit API and Token Service API. If you set HTTP referrer restrictions, make sure your domain is included.

```
// Symptoms of API key restriction issues:
// - signInWithPopup opens but immediately closes
// - signInWithEmailAndPassword returns auth/api-key-not-valid
// - Network tab shows 403 on identitytoolkit.googleapis.com

// Fix in Google Cloud Console > Credentials > API Keys:
// 1. Click your Firebase API key
// 2. Under API restrictions, ensure these APIs are allowed:
//    - Identity Toolkit API
//    - Token Service API
//    - Firebase Installations API
// 3. Under Application restrictions, add your domains
```

**Expected result:** API key restrictions allow Firebase Auth APIs and your app's domain.

## Complete code example

File: `auth-debug-helper.ts`

```typescript
import {
  getAuth,
  onAuthStateChanged,
  signInWithEmailAndPassword,
  GoogleAuthProvider,
  signInWithPopup,
  User,
} from 'firebase/auth'

const auth = getAuth()

export function waitForAuth(): Promise<User | null> {
  return new Promise((resolve) => {
    const unsubscribe = onAuthStateChanged(auth, (user) => {
      unsubscribe()
      resolve(user)
    })
  })
}

export async function safeEmailSignIn(
  email: string,
  password: string
): Promise<{ user?: User; error?: string }> {
  try {
    const { user } = await signInWithEmailAndPassword(auth, email, password)
    return { user }
  } catch (err: any) {
    const messages: Record<string, string> = {
      'auth/user-not-found': 'No account found with this email.',
      'auth/wrong-password': 'Incorrect password.',
      'auth/invalid-credential': 'Email or password is incorrect.',
      'auth/too-many-requests': 'Too many attempts. Please wait and try again.',
      'auth/network-request-failed': 'Network error. Check your connection.',
      'auth/operation-not-allowed': 'Email/password sign-in is not enabled.',
      'auth/unauthorized-domain': 'This domain is not authorized for auth.',
    }
    return { error: messages[err.code] || `Auth error: ${err.code}` }
  }
}

export async function safeGoogleSignIn(): Promise<{ user?: User; error?: string }> {
  try {
    const provider = new GoogleAuthProvider()
    const { user } = await signInWithPopup(auth, provider)
    return { user }
  } catch (err: any) {
    if (err.code === 'auth/popup-closed-by-user') {
      return { error: 'Sign-in popup was closed.' }
    }
    return { error: `Google sign-in error: ${err.code}` }
  }
}
```

## Common mistakes

- **Checking auth.currentUser on page load instead of waiting for onAuthStateChanged** — undefined Fix: Always use onAuthStateChanged to wait for auth initialization. currentUser is null until the persisted session loads, which takes a few hundred milliseconds.
- **Using the Firebase config from a different project or environment** — undefined Fix: Copy the config directly from Firebase Console > Project Settings > Your apps. Compare every field with what is in your code.
- **Not enabling the sign-in provider in the Firebase Console before using it in code** — undefined Fix: Go to Authentication > Sign-in method and enable each provider you use. For OAuth providers, also configure the client ID and secret.
- **Restricting the API key too aggressively in Google Cloud Console** — undefined Fix: Ensure your API key allows the Identity Toolkit API and Token Service API. Add your app's domains to the HTTP referrer restrictions.

## Best practices

- Always use onAuthStateChanged to detect the initial auth state instead of reading currentUser directly
- Catch and handle specific error codes from auth operations to provide clear feedback to users
- Keep your Firebase config in environment variables and verify they match the Console values
- Add all production and staging domains to the authorized domains list in Firebase Console
- Test authentication in an incognito window to rule out browser extension interference
- Check the browser network tab for failed requests to identitytoolkit.googleapis.com for API-level debugging
- Log auth errors with the error.code property, not just error.message, for consistent debugging

## Frequently asked questions

### Why does auth.currentUser return null even though I am signed in?

Firebase Auth loads the persisted session asynchronously. On page load, currentUser is null until initialization completes (200-500ms). Use onAuthStateChanged to wait for the auth state to resolve.

### What does auth/operation-not-allowed mean?

This error means the sign-in method is not enabled in the Firebase Console. Go to Authentication > Sign-in method and enable the provider you are trying to use.

### Why does Google sign-in work in development but not in production?

Your production domain is likely not in the authorized domains list. Go to Firebase Console > Authentication > Settings > Authorized domains and add your production URL.

### How do I debug auth issues on mobile devices?

Use remote debugging (Chrome DevTools for Android, Safari Web Inspector for iOS) to view console errors. On mobile, popup-based sign-in may fail due to popup blockers. Use signInWithRedirect instead.

### Can Firebase Auth work without an internet connection?

Firebase Auth caches the user session locally. A previously signed-in user remains authenticated offline. However, new sign-in and sign-up operations require an internet connection.

### Can RapidDev help troubleshoot complex Firebase Auth issues?

Yes, RapidDev's engineering team can diagnose and fix Firebase Auth problems including OAuth configuration, session management, and custom authentication flows.

---

Source: https://www.rapidevelopers.com/firebase-tutorial/how-to-fix-firebase-authentication-not-working
© RapidDev — https://www.rapidevelopers.com/firebase-tutorial/how-to-fix-firebase-authentication-not-working
