DIGI Byte
DIGI Byte

Reputation: 4164

Firebase Realtime Rest API with JavaScript

The Firebase Documentation has some useful curl operations but doesn't provide information regarding Cors, headers, and auth using JS Fetch. We are using a fetch-only solution as I am creating a client-based Firebase npm package where users might not have the firebase modules imported for several reasons, tree shaking, minified project, etc.

I imagine I need to pass on the Auth as a header, What about Cors and credentials?

Here is a crude example, is this sufficient? or are there other unforeseen issues?

const pushOptions = {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors',
    credentials: 'same-origin',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
}

var dataAPI = await fetch(databaseUrl+`/test.json`,pushOptions)
        .then(response => response.json())

Reference:

Upvotes: 1

Views: 1253

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50860

The documentation says you need to pass your Firebase ID in query parameter 'access_token' and not in any header. For example,

curl 'https://[PROJECT_ID].firebaseio/users/jack/name.json?access_token=CREDENTIAL'

But I ended up getting Unauthorized errors.

However, the Authenticate with an ID Token section in Firebase Auth REST API documentation says, "pass the ID token generated above as the auth=<ID_TOKEN> query string parameter". A sample curl request for the same would be:

curl 'https://[PROJECT_ID].firebaseio/users/jack/name.json?auth=CREDENTIAL'

This request worked as expected.

About CORS, this answer says,

Firebase uses a fully-permissive cross-origin resource sharing (CORS) policy, meaning that you can make requests to the Firebase servers from any origin. This is possible because Firebase does not use cookies or traditional sessions to govern which requests are authorized and which are not.

Here's a working example using Javascript fetch:

firebase.auth().onAuthStateChanged(async (user) => {
  const token = await firebase.auth().currentUser.getIdToken()
  
  const pushOptions = {
    method: 'GET',
  }

  const reqURL = "https://[PROJECT_ID].firebaseio.com" + `/path.json?auth=${token}`
  const dataAPI = await fetch(reqURL, pushOptions)
      .then(response => response.json())
      .then(res => console.log(res))
})

I just used the client SDK to get an ID Token quickly but it will work irrespective of from where the token is generated - client SDK or Auth REST API.

The REST API accepts the same Firebase ID tokens used by the client SDKs.

Upvotes: 2

Related Questions