|
| 1 | +--- |
| 2 | +title: Cloud Functions |
| 3 | +sidebar_position: 6 |
| 4 | +--- |
| 5 | + |
| 6 | +# Cloud Functions |
| 7 | + |
| 8 | +[Cloud Functions](https://firebase.google.com/docs/functions) allows you to run backend code in response to events triggered by Firebase features and HTTPS requests. For example, you want to automatically send a welcome email to users when they sign up for your app. You can do this using a Cloud Function that triggers on Firebase Authentication's user creation event. |
| 9 | + |
| 10 | +We allow you to write and deploy Firebase Cloud Functions directly within the platform. With an integrated code editor, writing JavaScript cloud functions is quick and user-friendly. Each function has customizable boilerplate settings, including pre-configured essentials like memory, region, and timeout. |
| 11 | + |
| 12 | +:::note |
| 13 | +You can find some interesting use cases [*here*](https://firebase.google.com/docs/functions/use-cases). |
| 14 | +::: |
| 15 | + |
| 16 | +## Adding Cloud Functions |
| 17 | + |
| 18 | +Let's see how to add a *Cloud Function* by building an example that generates logos based on user prompts. Here's how it looks: |
| 19 | + |
| 20 | +<div class="video-container"><iframe src="https://www.loom. |
| 21 | +com/embed/9ccf3523d9ce4564a712b6abad926b30?sid=ca4872c1-4cdb-4ea4-8b60-7d9011bef33e" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe></div> |
| 22 | + |
| 23 | +<p></p> |
| 24 | + |
| 25 | +The Cloud Function takes input from a TextField widget and initiates an API call to an [image generation API](https://platform.openai.com/docs/api-reference/images/create). Once the image URL is retrieved, it's displayed within an Image widget. |
| 26 | + |
| 27 | +Here are the step-by-step instructions to build such an example: |
| 28 | + |
| 29 | +1. [Add page state variables](#1-add-page-state-variables) |
| 30 | +5. [Build a page](#2-build-a-page) |
| 31 | +8. [Create and deploy Cloud Function](#3-create-and-deploy-cloud-function) |
| 32 | +11. [Optional: Add package](#4-optional-add-package) |
| 33 | +14. [Trigger Cloud Function](#5-trigger-cloud-function) |
| 34 | +17. [Optional: Use Cloud Function result](#6-optional-use-cloud-function-result) |
| 35 | + |
| 36 | +:::info[Before you Begin] |
| 37 | + |
| 38 | +* Make sure the project is on Blaze plan on Firebase. |
| 39 | +* Completed all steps in the [Firebase Setup](/data-and-backend/firebase/firebase-setup). |
| 40 | +::: |
| 41 | + |
| 42 | +### 1. Add page state variables |
| 43 | + |
| 44 | +For this example, you'll need to set up two [page state variables](/data-and-backend/state-management/page-state#1.-creating-page-state-variable): |
| 45 | + |
| 46 | +1. **generatingImage (*****Type: Boolean*****)**: This is used to control the visibility of a |
| 47 | +loading indicator during the logo creation process. Its value is set to *True* before initiating the API call and switched to *False* once the logo generation is complete. |
| 48 | +5. **logoImage (*****Type: ImagePath*****)**: This is used to hold the generated logo image. After a successful API call, the retrieved image URL is stored here, allowing the logo to be displayed in the Image widget. |
| 49 | + |
| 50 | + |
| 51 | +### 2. Build a page |
| 52 | + |
| 53 | +Let's add a page that allows users to enter the prompt. To speed up, you can add a page from the [template](/getting-started/adding-new-page#add-page) or use [AI Page Gen](/getting-started/adding-new-page#ai-gen-page). Here is the page added using AI Page Gen, and after some modification, it looks the below: |
| 54 | + |
| 55 | +Also, see how to [build a page layout](/widgets-and-components/ui-and-layout-101) if you want to build a page from scratch. |
| 56 | + |
| 57 | + |
| 58 | + |
| 59 | +Few things to note here: |
| 60 | + |
| 61 | +* We use the [ConditionalBuilder](/widgets-and-components/widgets/base-elements/conditionalbuilder) widget to show/hide the loading indicator based on the *generatingImage* variable. **Tip**: The Else branch of this widget is nothing but a ProgressBar inside the Container with a [rotating loop animation](/widgets-and-components/animations#4.-rotate). |
| 62 | +* The Image widget uses the *logoImage* variable to display the logo. |
| 63 | + |
| 64 | +### 3. Create and deploy Cloud Function |
| 65 | + |
| 66 | +To create and deploy a *Cloud Function* : |
| 67 | + |
| 68 | +1. Click on the **Cloud Functions** from the [*Navigation Menu*] |
| 69 | +(/getting-started/ui-builder/navigation-menu) (left side of your screen). |
| 70 | +5. Click **+ Add**. This will add the default newCloudFunction*.* |
| 71 | +8. Set the **Cloud Function Name**. |
| 72 | + |
| 73 | +#### Boilerplate Settings |
| 74 | + |
| 75 | +On the right side, you can configure the following Boilerplate Settings: |
| 76 | +1. **Memory Allocation**: You can specify the amount of memory your function should have when |
| 77 | + it's executed based on its complexity and needs. This setting is crucial as it influences the function's performance and the cost of running it. More memory can enhance performance for intensive tasks but also increase costs. |
| 78 | +5. **Timeout (s)**: This refers to the maximum amount of time, in seconds, that a function is allowed to run before it is automatically terminated. If your function takes longer to execute, increasing the timeout setting may be necessary. However, be aware that longer timeouts can incur higher costs since billing is based on execution time. |
| 79 | +8. **Require Authentication**: Turn on this setting if you want users to be authenticated to execute this cloud function. |
| 80 | +11. **Cloud Function Region**: This determines the geographical location of the servers where your functions are hosted and executed. Ideally, you should keep this same as your *Default GCP resource location* and the Cloud Function Region specified in the Firebase Advanced Settings. |
| 81 | + |
| 82 | + |
| 83 | + |
| 84 | +#### Configuring Input & Output |
| 85 | + |
| 86 | +Your cloud function might need some data to process and return the result. You can do so |
| 87 | +by configuring the input and output. |
| 88 | + |
| 89 | +1. To receive output from a Cloud Function, enable the **Return Value** and choose an |
| 90 | + appropriate Type for the output, like 'String' for text. For this example, set it to *ImagePath* to get the URL of the generated logo. |
| 91 | +5. To input data: Click **+ Add parameters**. **Name** the parameter, select its **Type**, choose single or multiple items (**Is List** option), and uncheck **Nullable** if the value can be null. For this example, add a parameter 'prompt' with *Type* set to *String*. |
| 92 | +8. When using [Custom Data Types](/data-and-backend/custom-data-types), Cloud Function expects JSON, matching each field in the Data Type to a key-value pair in the JSON. If the Data Type is a list, the function expects a list of JSONs. For example, for a custom data type named 'Person' with fields 'Name' and 'Age,' the function should return: |
| 93 | + |
| 94 | + ``` |
| 95 | + //JSON: |
| 96 | + { "Name": "John", "Age": 30 } |
| 97 | + |
| 98 | + //Example Cloud Function Code: |
| 99 | + return { |
| 100 | + "name": person.name, |
| 101 | + "age": person.age |
| 102 | + }; |
| 103 | +``` |
| 104 | + |
| 105 | +For a list, the function should return: |
| 106 | + |
| 107 | + |
| 108 | +``` |
| 109 | + //JSON |
| 110 | + [ { "Name": "John", "Age": 30 }, { "Name": "Jane", "Age": 25 } ] |
| 111 | + |
| 112 | + //Example Cloud Function Code: |
| 113 | + return filteredpersons.map(filteredpersons => { |
| 114 | + return { |
| 115 | + "name": filteredpersons.name, |
| 116 | + "age": filteredpersons.age |
| 117 | + }; |
| 118 | + }); |
| 119 | +``` |
| 120 | + |
| 121 | +#### To deploy |
| 122 | +1. Click the `[</>]` icon to view the boilerplate code; a popup will open with the updated |
| 123 | +code, and then click **`</> Copy to Editor`**. **Tip**: To see if you are able to deploy the cloud function (before adding your own code), proceed directly with steps 8 and 9. |
| 124 | +2. Inside the code editor, add the cloud function code. **Tip**: You can copy the boilerplate code |
| 125 | + to [ChatGPT](https://chat.openai.com/) and ask it to write the desired code based on that. |
| 126 | +3. Click **Save Cloud Function**. |
| 127 | +4. Click **Deploy**. |
| 128 | + |
| 129 | +Here's the code used for this example: |
| 130 | + |
| 131 | +``` |
| 132 | +const functions = require('firebase-functions'); |
| 133 | +const admin = require('firebase-admin'); |
| 134 | +const https = require('https'); |
| 135 | +
|
| 136 | +exports.logoMaker = functions.region('us-central1') |
| 137 | + .runWith({ |
| 138 | + timeoutSeconds: 10, |
| 139 | + memory: '512MB' |
| 140 | + }).https.onCall((data, context) => { |
| 141 | + return new Promise((resolve, reject) => { |
| 142 | + const prompt = data.prompt; |
| 143 | + if (!prompt) { |
| 144 | + reject(new functions.https.HttpsError('invalid-argument', 'No prompt provided')); |
| 145 | + return; |
| 146 | + } |
| 147 | +
|
| 148 | + const postData = JSON.stringify({ |
| 149 | + model: "dall-e-3", |
| 150 | + prompt: prompt, |
| 151 | + n: 1, |
| 152 | + size: "1024x1024" |
| 153 | + }); |
| 154 | +
|
| 155 | + const options = { |
| 156 | + hostname: 'api.openai.com', |
| 157 | + port: 443, |
| 158 | + path: '/v1/images/generations', |
| 159 | + method: 'POST', |
| 160 | + headers: { |
| 161 | + 'Content-Type': 'application/json', |
| 162 | + 'Authorization': `Bearer YOUR-APIKEY`, |
| 163 | + 'Content-Length': postData.length |
| 164 | + } |
| 165 | + }; |
| 166 | +
|
| 167 | + const req = https.request(options, (res) => { |
| 168 | + let responseBody = ''; |
| 169 | +
|
| 170 | + res.on('data', (chunk) => { |
| 171 | + responseBody += chunk; |
| 172 | + }); |
| 173 | +
|
| 174 | + res.on('end', () => { |
| 175 | + try { |
| 176 | + const responseJSON = JSON.parse(responseBody); |
| 177 | + if (responseJSON.data && responseJSON.data.length > 0) { |
| 178 | + // Retrieve the URL of the first image |
| 179 | + const firstImageUrl = responseJSON.data[0].url; |
| 180 | + resolve(firstImageUrl); |
| 181 | + } else { |
| 182 | + reject(new functions.https.HttpsError('not-found', 'No images found')); |
| 183 | + } |
| 184 | + } catch (error) { |
| 185 | + reject(new functions.https.HttpsError('internal', 'Error processing response', error)); |
| 186 | + } |
| 187 | + }); |
| 188 | + }); |
| 189 | +
|
| 190 | + req.on('error', (error) => { |
| 191 | + reject(new functions.https.HttpsError('internal', 'Error generating image', error)); |
| 192 | + }); |
| 193 | +
|
| 194 | + req.write(postData); |
| 195 | + req.end(); |
| 196 | + }); |
| 197 | + }); |
| 198 | +``` |
| 199 | + |
| 200 | +:::tip[Important] |
| 201 | +Always regenerate and use the updated boilerplate code or adjust your own code accordingly whenever there are changes in the code, boilerplate settings, or input/output parameters. |
| 202 | +::: |
| 203 | + |
| 204 | +<div class="video-container"><iframe src="https://www.loom. |
| 205 | +com/embed/1dc13a747b6b4f6d9c9f6d3e1721e488?sid=a756ed68-f20a-4723-8a89-bc1462ede168" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe></div> |
| 206 | + |
| 207 | + |
| 208 | + |
| 209 | +### 4. Optional: Add package |
| 210 | + |
| 211 | +Your cloud function may require third-party packages to work. You can include any npm package (dependency) by listing it in the `package.json` file. This file not only manages the npm package dependencies for your functions but also holds project metadata, sets up scripts for tasks such as deployment and outlines the compatible Node.js versions. |
| 212 | + |
| 213 | +To add a dependency, open the `package.json` file and specify your package in the `dependencies` section. |
| 214 | + |
| 215 | + |
| 216 | + |
| 217 | +### 5. Trigger Cloud Function |
| 218 | + |
| 219 | +The newly created *Cloud Function* will be available as an action when you are adding one. For this example, on click of a button, we'll first set the *generatingImage*to *True* and then [trigger the Cloud Function](/actions/actions/cloud-function). |
| 220 | + |
| 221 | +<div class="video-container"><iframe src="https://www.loom. |
| 222 | +com/embed/5c712863f95c4fcabd5c3851a3cbe56b?sid=a7ac875f-11b5-4b5a-b3e2-8ae03ce49571" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe></div> |
| 223 | + |
| 224 | + |
| 225 | +### 6. Optional: Use Cloud Function result |
| 226 | + |
| 227 | +To use the *Could Function* result, ensure you provide the *Action Output Variable Name* while adding the action, and then you can access it via the **Set from Variable menu > Action Outputs > [Action Output Variable Name]**. |
| 228 | + |
| 229 | +For this example, we'll use the result (i.e., generated logo image URL) and set it to *logoImage*variable. Here's how you do it: |
| 230 | + |
| 231 | +<div class="video-container"><iframe src="https://www.loom. |
| 232 | +com/embed/0c4306c1951a4d9099aa96324c7561af?sid=69709110-ad60-4e98-bf53-36a50a99e425" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe></div> |
| 233 | + |
| 234 | + |
| 235 | + |
| 236 | +## FAQs |
| 237 | + |
| 238 | +<details> |
| 239 | +<summary>I am getting Cloud Function Deployment Errors</summary> |
| 240 | + |
| 241 | + |
| 242 | + |
| 243 | +<p></p> |
| 244 | + |
| 245 | +If you encounter deployment errors, it may be helpful to check out [this community post](https://community.flutterflow.io/discussions/post/how-to-fix-cloud-function-deployment-errors-all-solutions-discussion-wgfMLgpLrBlmnUI) for possible solutions and insights. |
| 246 | + |
| 247 | +</details> |
| 248 | + |
| 249 | + |
| 250 | + |
| 251 | + |
0 commit comments