How can I properly simulate a cloud function locally so that it has all data as when being invoked on firebase servers? (e.g. the
context.auth
)
I am serving my project with firebase serve
, it runs ok on http://localhost:5000/
, however, my cloud functions are being called from https://us-central1-<my-app>.cloudfunctions.net/getUser
. (The function is not even deployed.)
To avoid XY problem, I am trying to debug my function, but calling it from firebase shell results in context.auth
being undefined, same when calling via postman from http://localhost:5000/<my-app>/us-central1/getUser
.
This is my ./functions/src/index.ts
file
import * as functions from 'firebase-functions'
import admin from 'firebase-admin'
import { inspect } from 'util'
admin.initializeApp()
export const getUser = functions.https.onCall((data, context) => {
console.debug('== getUser called =========================================')
console.log('getUser', inspect(data), inspect(context.auth))
return admin.database().ref('userRights/admin').child(context.auth.uid).once('value', snapshot => {
console.log(snapshot.val())
if (snapshot.val() === true) {
return 'OK'
// return {status: 'OK'}
} else {
return 'NOK'
// return {status: 'error', code: 401, message: 'Unauthorized'}
}
})
})
file ./firebase.functions.ts
import { functions } from '~/firebase'
export const getUser = functions.httpsCallable('getUser')
Consumer ./src/pages/AdminPanel/index.tsx
import { getUser } from '~/firebase.functions'
//...
getUser({myDataX: 'asd'}).then(response => console.debug('response', response))
You can connect an HTTP function to Firebase Hosting. Requests on your Firebase Hosting site can be proxied to specific HTTP functions. This also allows you to use your own custom domain with an HTTP function. Learn more about connecting Cloud Functions to Firebase Hosting.
Serverless APIs and your First Endpoint. Firebase Functions enables you to use the ExpressJS library to host a Serverless API.
UPDATE - April/2021
As of April/2021, method useFunctionsEmulator
has been deprecated. It is suggested to use method useEmulator(host, port)
instead.
Original post:
By default, firebase serve
sends queries to CLOUD function instead of localhost, but it is possible to change it to to point to localhost.
@gregbkr found a workaround for that at this github thread.
You basically add this after firebase initialization script (firebase/init.js) in html head.
<script>
firebase.functions().useFunctionsEmulator("http://localhost:5001");
</script>
Make sure to REMOVE it when deploying to SERVER
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With