Test you .onCall firebase functions locally.

Fredric Cliver
2 min readSep 6, 2020

--

When you try to test your firebase functions in your local environment, you may face to this

Access to fetch at 'https://[project-id].cloudfunctions.net/[functions-name]' from origin 'http://localhost:5000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.POST https://[project-id].cloudfunctions.net/[functions-name] net::ERR_FAILEDError: internal
at new y (error.ts:66)
at w (error.ts:175)
at A.<anonymous> (service.ts:244)
at tslib.es6.js:100
at Object.next (tslib.es6.js:81)
at r (tslib.es6.js:71)

For you testing on a local environment, you can execute the firebase emulator with these commands

> firebase emulators:startor> firebase serve

What I’m introducing way works in both.

/firebase.json

/public/index.html

You have to care about using defer.
If you remove defer keyword from requesting ./index.js it makes an error what cannot find a firebase module.

/functions/index.js

.onCall method is different with .onRequest method.
And you should use a return rather than use “response.send(~)”

/public/index.js

.useFunctionsEmulator function make set you use local functions, not server one.

And I recommend you put that one line for a local testing environment into somewhere like init.js for just the first time once.

And you might be able to use environmental conditions

But this is for server-side. And in your front-end script, you can use this if block

if (location.hostname == "127.0.0.1" || 
location.hostname == "localhost") {
console.log('This is local emulator environment')
functions.useFunctionsEmulator("http://localhost:5001")
}

If you’re using Typescript,

if (location.hostname == "127.0.0.1" || 
location.hostname == "localhost") {
console.log('This is local emulator environment')
firebase.functions().useFunctionsEmulator("http://localhost:5001")
}
}
https://firebase.google.com/docs/reference/android/com/google/firebase/functions/FirebaseFunctions?hl=ja#useEmulator(java.lang.String,%20int)

But, in a google document, they say this method was deprecated. But, the Document is wrong. There is no useEmulator method, not useFunctionsEmulator method.

Just use .useFunctionEmulator method.

--

--

Fredric Cliver
Fredric Cliver

Written by Fredric Cliver

13+ years in the digital trenches. I decode complex tech concepts into actionable insights, focusing on AI, Software Engineering, and emerging technologies.

No responses yet