How to set up Cloud Firestore for static hosted website

Viewed 1752

The Firestore docs only shows how to set up Firestore using firebase-admin, which seems to me like basically a server-side solution. Even if we are talking about using Cloud Functions, that is still a mini-server with an extra abstraction layer between the browser and the database. I'm' trying to figure out how to do similar setup as would be used for accessing the Realtime Database directly from browser code.

At 5 minutes into YouTube: Getting Started With Cloud Firestore on the Web | Complete Tutorial provided by Google, I see exactly this type of configuration being used, except, now after initializing the app, we call firestore() method instead of database() method to get the root reference.

I've reinitialized the project with firestore turned on, and have the project rules currently set to allow anyone to access it. But for me the firebase() method is not included in my firebase instance.

const firebase = require('firebase')

const config = {
  apiKey: 'long_ugly_string',
  authDomain: 'my_app_id.firebaseapp.com',
  databaseURL: 'https://my_app_id.firebaseio.com',
  projectId: 'my_app_id',
}

firebase.initializeApp(config)

console.log(firebase.firebase) // undefined
const firestore = firebase.firestore() // TypeError: firebase.firestore is not a function

I also tried creating a 100% brand new project to make sure the issue was not being caused by old settings lingering from the Realtime Database installation. But I have the same issue with the new project. My firebase instance ends up with a database() method, but no firestore() method.

1 Answers

Thanks to comment from @Sidney, I was able to work out the issue. I was in-fact looking at the node.js tab and not the web tab in the docs. The missing element was a call to require('firebase/firestore') to make it available to the firebase module. Here is the corrected setup code:

const firebase = require('firebase')
require('firebase/firestore') // *** this line was missing ***

const config = {
  apiKey: 'long_ugly_string',
  authDomain: 'my_app_id.firebaseapp.com',
  databaseURL: 'https://my_app_id.firebaseio.com',
  projectId: 'my_app_id',
}

firebase.initializeApp(config)

const firestore = firebase.firestore() 

// rest of code ...
Related