Home > Back-end >  How to let a signed in user create a document in firestore (SDK Web version 9 modular)
How to let a signed in user create a document in firestore (SDK Web version 9 modular)

Time:10-06

I'm trying to let a signed-in users create a document on the Firestore Database. For that I want to use the secureToken which gets created by Firebase Authentication after a user logs in with the email/password method.

In the Firebase Realtime Database for example, I can just make a post request with axios where I include the secureToken like this:

axios.post('https://project_name.europe-west1.firebasedatabase.app/posts.json?auth='
  token, postData)

and in the Rules of the Realtime Database I have:

{
  "rules": {
    ".read": true,
    ".write": "auth != null"
  }
}

So that works fine so far.

But with the SDK 9 with the modular approach I don't know how to pass on the secureToken.

Here is the addDoc request:

const docRef = await addDoc(collection(db, 'posts'), { postData })

I was reading the cloud-documentation for hours, but couldn't find out how to proceed from here.

Only found this for adding data in general: https://firebase.google.com/docs/firestore/manage-data/add-data

and this for securely query data: https://firebase.google.com/docs/firestore/security/rules-query

CodePudding user response:

If you are using Firebase SDK for authentication as well then you don't need to add any token. The SDK will check for auth state and do that for you.

const docRef = await addDoc(collection(db, 'posts'), { postData })

The above operation will add a document in posts collection if your Firestore security rules allow the current user to write there.


Are you using REST API for authentication as well? Then you you might have to use REST API for Firestore as well and pass the auth token yourself.

  • Related