Search code examples
firebasegoogle-cloud-firestorenext.jsfirebase-securitygetserversideprops

Next.js getServerSideProps getDocs with Firebase Firestore rules


if i am using this rules at firestore

match /{document=**} {
  allow read, write: if  true;
}

getServerSideProps can get my data from firestore but if start using

match /{document=**} {
  allow read, write: if request.auth != null;
}

i get

[Error [FirebaseError]: Missing or insufficient permissions.] { digest: undefined }

but im was logged in with firebase authentication

trying to use

  const auth = getAuth();
  
  // Очікуємо на зміну стану авторизації користувача
  await new Promise((resolve) => {
    onAuthStateChanged(auth, (user) => {
      resolve(user);
    });
  });

but didnt help


Solution

  • The first rule is working because is allowing everybody to read/write without need to be logged, the second one on the other side is allowing only logged users. The problem you are facing with getServerSideProps is that this code is executed on the server not on client side and the server is not having access to the auth state.

    To fix your situation you can use firestore admin, here is well written how you can achieve this.