Search code examples
node.jsdatabasefirebasenext.jsgoogle-cloud-firestore

Firestore error "User document does not exist"


I'm working on a project similar to Linktree and have implemented Firebase for authentication and Firestore for the database. The authentication system is functioning correctly, and user data is being saved in a collection named users. However, when I redirect to the user's dashboard, I'm seeing undefined in areas where data should be displayed.

On the user's dashboard code I've imported everything necessary for the database fetching.

import { db, auth } from "@/lib/firebaseConfig";
import { getDoc, doc } from "firebase/firestore";
import { signOut, onAuthStateChanged } from "firebase/auth";



 useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, async (user) => {
      if (user) {
        console.log("User authenticated:", user.uid); // Add a log to check user UID
        try {
          const userDocRef = doc(db, "users", user.uid);
          const userDoc = await getDoc(userDocRef);

          if (userDoc.exists()) {
            console.log("User document found:", userDoc.data()); // Log the data
            setUserData(userDoc.data());
          } else {
            console.log("User document does not exist."); // Log for debugging
            alert("User document does not exist.");
          }
        } catch (error) {
          console.error("Error fetching user data:", error);
          alert(
            `Error fetching user data: ${
              error instanceof Error ? error.message : String(error)
            }`
          );
        }
      } else {
        console.log("No user is authenticated. Redirecting to login.");
        router.push("/"); // Redirect to home or login if no user is signed in
      }
    });

    return () => unsubscribe();
  }, [router]);

here is my firebaseConfig.ts file

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
    apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
    authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
    projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
    storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
    messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
    appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
    measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
};

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

export { db, auth };

This is my latest firestore rules

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read, write: if true;
    }
  }
}

before it was

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    // Allow read and write access to authenticated users on their own documents in the "users" collection
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
  }
}

firestore users collection image

user's dashboard image

I have tried changing the rules multiple times, including using an actual user's uid to the code, but nothing has worked. I also consulted various AI tools, but none have been effective in this case.


Solution

  • The grenishrai document ID in your first screenshot does not look like a UID, so it doesn't match up with what your code does here:

    const userDocRef = doc(db, "users", user.uid);
    

    To make your code work, ensure that you write to a document reference that was constructed in this exact same way.