How to fix PERMISSION_DENIED: User is not authenticated in Firebase

FirebaseBEGINNERHIGHUpdated Dec 22, 2025· 227 views

The "PERMISSION_DENIED: User is not authenticated" error occurs when you attempt to access Firestore or Realtime Database without signing in a user first. Firebase security rules require authentication by default, and unauthenticated requests are blocked to protect your data.

Quick fix

Fixes PERMISSION_DENIED: User is not authenticated

import { initializeApp } from "firebase/app";
import { getAuth, signInAnonymously, onAuthStateChanged } from "firebase/auth";
import { getFirestore, collection, getDocs } from "firebase/firestore";

const firebaseApp = initializeApp({
  apiKey: "YOUR_API_KEY",
  projectId: "YOUR_PROJECT_ID",
  // ... other config
});

const auth = getAuth(firebaseApp);
const db = getFirestore(firebaseApp);

// Sign in anonymously first
signInAnonymously(auth)
  .then(() => {
    // Now safe to access Firestore
    return getDocs(collection(db, "users"));
  })
  .then(snapshot => {
    console.log("Data retrieved:", snapshot.docs.map(doc => doc.data()));
  })
  .catch(error => console.error("Error:", error));
  1. Sign in a user before accessing the database
  2. Use onAuthStateChanged to wait for authentication
  3. Review and update your security rules
  4. Enable anonymous authentication if needed
firebase — error
import { initializeApp } from "firebase/app";
import { getAuth, signInAnonymously, onAuthStateChanged } from "firebase/auth";
import { getFirestore, collection, getDocs } from "firebase/firestore";
const firebaseApp = initializeApp({
apiKey: "YOUR_API_KEY",
projectId: "YOUR_PROJECT_ID",
// ... other config
});
const auth = getAuth(firebaseApp);
const db = getFirestore(firebaseApp);
// Sign in anonymously first
signInAnonymously(auth)
.then(() => {
// Now safe to access Firestore
return getDocs(collection(db, "users"));
})
.then(snapshot => {
console.log("Data retrieved:", snapshot.docs.map(doc => doc.data()));
})
.catch(error => console.error("Error:", error));
PERMISSION_DENIED: User is not authenticated

What this error means

The "PERMISSION_DENIED: User is not authenticated" error means your code is trying to read or write data in Firebase (Firestore or Realtime Database) while no user is logged in. Firebase security rules check the `request.auth` context to determine if an operation is allowed. When `request.auth` is null (indicating no authenticated user), the default security rules deny the operation to prevent unauthorized access. This is a security feature protecting your database from malicious or unintended access.

Typical symptoms

  • Firestore or Realtime Database queries return "PERMISSION_DENIED: User is not authenticated" error
  • Database operations fail immediately after app initialization, before user logs in
  • Error message appears in browser console or server logs when accessing data
  • Write operations fail with permission error even though rules appear permissive
  • Anonymous sign-in methods show permission errors despite being enabled in rules

Common causes

  1. User is not authenticated before attempting to access Firestore or Realtime Database
  2. Authentication initialization happens after database query attempts
  3. Security rules require authentication (check `if request.auth != null`) but no user is logged in
  4. Session expired or authentication was revoked before the operation
  5. Using wrong authentication provider or misconfigured Firebase app initialization

How to fix "PERMISSION_DENIED: User is not authenticated"

1Sign in a user before accessing the database

The most direct fix is to ensure a user is authenticated before any database operations:

Web/JavaScript:

javascript
import { initializeApp } from "firebase/app";
import { getAuth, signInAnonymously, onAuthStateChanged } from "firebase/auth";
import { getFirestore, collection, getDocs } from "firebase/firestore";

const firebaseApp = initializeApp({
  apiKey: "YOUR_API_KEY",
  projectId: "YOUR_PROJECT_ID",
  // ... other config
});

const auth = getAuth(firebaseApp);
const db = getFirestore(firebaseApp);

// Sign in anonymously first
signInAnonymously(auth)
  .then(() => {
    // Now safe to access Firestore
    return getDocs(collection(db, "users"));
  })
  .then(snapshot => {
    console.log("Data retrieved:", snapshot.docs.map(doc => doc.data()));
  })
  .catch(error => console.error("Error:", error));

React Pattern:

javascript
import { useEffect, useState } from "react";
import { getAuth, signInAnonymously } from "firebase/auth";
import { getFirestore, collection, getDocs } from "firebase/firestore";

export function MyComponent() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const auth = getAuth();
    const db = getFirestore();

    // Sign in and load data
    signInAnonymously(auth)
      .then(() => getDocs(collection(db, "users")))
      .then(snapshot => {
        setData(snapshot.docs.map(doc => doc.data()));
        setLoading(false);
      })
      .catch(error => {
        console.error("Error:", error);
        setLoading(false);
      });
  }, []);

  if (loading) return <div>Loading...</div>;
  return <div>{JSON.stringify(data)}</div>;
}
2Use onAuthStateChanged to wait for authentication

Instead of immediately querying the database, wait for the authentication state to initialize:

javascript
import { getAuth, onAuthStateChanged } from "firebase/auth";
import { getFirestore, collection, getDocs } from "firebase/firestore";

const auth = getAuth();
const db = getFirestore();

// Wait for auth state to initialize
onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in, now safe to query database
    getDocs(collection(db, "users"))
      .then(snapshot => {
        console.log("Data:", snapshot.docs.map(doc => doc.data()));
      })
      .catch(error => console.error("Query error:", error));
  } else {
    // User is not signed in
    console.log("User not authenticated. Sign in first.");
  }
});

This pattern is essential because onAuthStateChanged is asynchronous and triggers when Firebase connects to the backend. Queries before this completes will fail with permission denied.

3Review and update your security rules

Check your Firestore/Realtime Database security rules:

1. Go to [Firebase Console](https://console.firebase.google.com)
2. Navigate to Firestore Database → Rules (or Realtime Database → Rules)
3. Review the current rules

For development testing only (insecure):

bash
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;  // ONLY for testing!
    }
  }
}

For authenticated users (recommended):

bash
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}

For user-specific data:

bash
match /users/{userId} {
  allow create: if request.auth != null;
  allow read, update, delete: if request.auth != null && request.auth.uid == userId;
}
4Enable anonymous authentication if needed

If your app allows unauthenticated users, enable anonymous sign-in:

1. Go to [Firebase Console](https://console.firebase.google.com)
2. Navigate to Authentication → Sign-in method
3. Enable Anonymous provider
4. Update your security rules to allow anonymous access:

bash
match /public/{document=**} {
  allow read: if request.auth != null;  // Any authenticated user (including anonymous)
}

Then sign in anonymously before queries:

javascript
import { signInAnonymously } from "firebase/auth";

const auth = getAuth();
await signInAnonymously(auth);
// Now database queries will work
5Check app initialization order

Ensure Firebase is properly initialized before any database access:

javascript
import { initializeApp } from "firebase/app";
import { getAuth, signInAnonymously } from "firebase/auth";
import { getFirestore, collection, getDocs } from "firebase/firestore";

// Step 1: Initialize Firebase
const app = initializeApp({
  apiKey: "YOUR_API_KEY",
  projectId: "YOUR_PROJECT_ID",
  // ... other config from Firebase Console
});

// Step 2: Get references
const auth = getAuth(app);  // Pass app instance explicitly
const db = getFirestore(app);

// Step 3: Sign in
await signInAnonymously(auth);

// Step 4: Now access database
const snapshot = await getDocs(collection(db, "users"));
console.log("Success:", snapshot.docs);

Common mistake: calling getAuth() or getFirestore() before initializeApp() completes.

Advanced notes

If using Firebase with Next.js or SSR frameworks, authentication state is not available on the server, so all Firestore queries must happen client-side within a browser context. Use "use client" in React Server Components to move code to the browser. For server-side database access, use the Firebase Admin SDK which bypasses security rules entirely. If using the Firebase Emulator Suite locally, ensure your connectFirestoreEmulator() is called before any queries and that the emulator is running on the expected port (default 8080). The error can also occur briefly during app initialization before onAuthStateChanged fires—this is expected and resolves once initialization completes.

Frequently asked questions

What does "PERMISSION_DENIED: User is not authenticated" mean?
The "PERMISSION_DENIED: User is not authenticated" error means your code is trying to read or write data in Firebase (Firestore or Realtime Database) while no user is logged in. auth context to determine if an operation is allowed. auth is null (indicating no authenticated user), the default security rules deny the operation to prevent unauthorized access.
How do I fix "PERMISSION_DENIED: User is not authenticated"?
The "PERMISSION_DENIED: User is not authenticated" error occurs when you attempt to access Firestore or Realtime Database without signing in a user first. Firebase security rules require authentication by default, and unauthenticated requests are blocked to protect your data.
What causes "PERMISSION_DENIED: User is not authenticated"?
User is not authenticated before attempting to access Firestore or Realtime Database Authentication initialization happens after database query attempts Security rules require authentication (check if request.auth != null) but no user is logged in
Is the "PERMISSION_DENIED: User is not authenticated" error serious?
Yes. This is a high-severity error that usually blocks work until it is fixed, but the steps above resolve it.

Official resources & further reading