Setup Cloud Functions With Firebase Hosting

Firebase Hosting Test Cloud Functions

Setup Frebase CLI.

Initialize Cloud Functions at firebase project directory (not in public directory).

You get to select JavaScript or TypeScript, with option to enable ESLint.

firebase init functions

A functions directory is created with index.js, node_modules and some other files.

Edit functions/index.js. We shall create a cloud functions which accept and return json data.

const functions = require('firebase-functions');exports.test_message_json = functions.https.onRequest((request, response) => {  const message = request.body.message;  response.status(200).json({    message: message  });});

Run deploy at project root directory.

firebase deploy

NOTE: This seems to deploy both firebase hosting and cloud functions. It seems to work the same even if run in the functions directory.

NOTE: To deploy cloud functions only run firebase deploy --only functions.

I can test the new cloud functions: https://us-central1-PROJECT_NAME.cloudfunctions.net/test_message_json

curl --header "Content-Type: application/json" \  --request POST \  --data '{"message": "Hello"}' \  https://us-central1-nuanxindan.cloudfunctions.net/test_message_json

There are multiple ways to deploy HTTP cloud functions, are they are all listed at Firebase Console -> Develop -> Functions.

NOTE: Refer to Google Cloud Functions vs Cloud Functions for Firebase.

Direct hosting requests to cloud functions

Cloud functions have url such as this: https://us-central1-PROJECT_NAME.cloudfunctions.net/test_message_json, which make JavaScript ajax call from your domain (e.g. https://www.mydomain.com) shall bump into CORS exception.

Access to fetch at 'https://us-central1-PROJECT_NAME.cloudfunctions.net/test_message_json' from origin 'http://www.mydomain.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

To solve this issues, there are 2 solutions:

Edit firebase.json.

{  "hosting": {    "public": "public",    "ignore": [      "firebase.json",      "**/.*",      "**/node_modules/**"    ],    "rewrites": [      {        "source": "/functions/test_message_json",        "function": "test_message_json"      }    ]  },  "functions": {    "predeploy": [      "npm --prefix \"$RESOURCE_DIR\" run lint"    ],    "source": "functions"  }}

Local Test

firebase serve

NOTE: You can disable local cloud functions endpoint by using firebase serve --only hosting.

=== Serving from '/code/firebase/PROJECT_NAME'...

✔  functions: Using node@8 from host.
✔  functions: Emulator started at http://localhost:5001
i  functions: Watching "/code/firebase/PROJECT_NAME/functions" for Cloud Functions...
i  hosting: Serving hosting files from: public
✔  hosting: Local server: http://localhost:5000
i  functions: HTTP trigger initialized at http://localhost:5001/PROJECT_NAME/us-central1/test_message_json

I can access the cloud functions at http://localhost:5000/functions/test_message_json.

Rewrite Behaviour for Local Test

If you run firebase serve (both hosting and functions), request /functions/test_message_json will map to http://localhost:5001/PROJECT_NAME/us-central1/test_message_json.

[hosting] Rewriting /functions/test_message_json to http://localhost:5001/PROJECT_NAME/us-central1/test_message_json for local Function test_message_json

If you run firebase serve --only hosting, request /functions/test_message_json will map to production server: https://us-central1-PROJECT_NAME.cloudfunctions.net/test_message_json

[hosting] Rewriting /functions/test_message_json to https://us-central1-PROJECT_NAME.cloudfunctions.net/test_message_json for live Function test_message_json

Deployment

firebase deploy

I can access the cloud functions at via the following URLs:

  • https://www.mydomain.com/functions/test_message_json
  • https://us-central1-PROJECT_NAME.cloudfunctions.net/test_message_json

NOTE: Refer to Call Cloud Functions From Web.

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.