Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

firebase serve: From a locally served app, call locally served functions

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))
like image 328
Qwerty Avatar asked Jul 02 '18 15:07

Qwerty


People also ask

Does Firebase use HTTP requests?

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.

Can I use Firebase with Express?

Serverless APIs and your First Endpoint. Firebase Functions enables you to use the ExpressJS library to host a Serverless API.


1 Answers

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

like image 110
GorvGoyl Avatar answered Oct 10 '22 16:10

GorvGoyl