TECH

Vol.124

author

N.U.

The complete guide to getting started with Cloud Functions for firebase

#サーバーレス#クラウドサービス#開発#Faas#Cloud Function#Firebase
We've been covering serverless architecture in our TIPS series lately. This time, we're taking a closer look at Cloud Functions for Firebase. This isn't a brand-new technology — it's a fairly mature service with a solid track record. That's precisely why we wanted to create a practical guide: not just for beginners, but also for developers who've used it before and find themselves asking, "Wait, what do I need again?" We hope this serves as your go-to reference.
stuffstuff

What Is Cloud Functions for Firebase?

<p>Cloud Functions for Firebase is a cloud service provided by Google. It allows you to run code without building or maintaining your own server infrastructure.</p>

Prerequisites

Step 1: Create a Google account.
Step 2: Open the Firebase Console using the account from Step 1.
https://console.firebase.google.com/
Step 3: Click [Create a project] and follow the on-screen instructions to set up your project.

stuffstuff

Step 4: Configure users and permissions as needed.
Click the [Settings icon] in the top-left corner, then go to [Users and permissions] to open the settings screen.<br>Note: Users with Editor permissions cannot deploy Functions.

stuffstuff

Step 5: Upgrade your billing plan.
Cloud Functions is not available on the free tier, so you'll need to switch to the pay-as-you-go Blaze plan.

Project setup

Once the prerequisites are in place, it's time to configure your project.

Creating and Moving to a Local Folder

First, create a folder on your local machine and navigate into it.

mkdir test-project
cd test-project

Setting Up the Firebase CLI

Install the Firebase CLI so that you can use firebase commands in your project.

npm install -g firebase-tools

Logging in to Firebase

firebase login

When you run the command above, your browser will open automatically. Select your account to log in. You have successfully logged in once the following message appears:

❯ firebase login
Waiting for authentication...
device to log in:
✔  Success! Logged in as [email protected]

Initializing the App

To initialize the app, run the following command:

firebase init

Once executed, the following output will appear:

❯ firebase init

######## #### ########  ######## ########     ###     ######  ########
     ##        ##  ##     ## ##       ##     ##  ##   ##  ##       ##
     ######    ##  ########  ######   ########  #########  ######  ######
     ##        ##  ##    ##  ##       ##     ## ##     ##       ## ##
     ##       #### ##     ## ######## ########  ##     ##  ######  ########

You're about to initialize a Firebase project in this directory:

/Users/XXX/Documents/test-project

Selecting Configuration Files to Generate

Move the cursor to the service you want to use and press Space to select it. For this guide, we will select only "Functions."

? Which Firebase CLI features do you want to set up for this folder? Press Space to select features, then Enter to confirm your choices.
◯ Database: Deploy Firebase Realtime Database Rules
◯ Firestore: Deploy rules and create indexes for Firestore
❯◉ Functions: Configure and deploy Cloud Functions
◯ Hosting: Configure and deploy Firebase Hosting sites
◯ Storage: Deploy Cloud Storage security rules
◯ Emulators: Set up local emulators for Firebase features

Select "Use an existing project."

? Please select an option: (Use arrow keys)
❯ Use an existing project
Create a new project
Add Firebase to an existing Google Cloud Platform project
Don't set up a default project

Select the project you created during the preparation step.

? Please select an option: Use an existing project
? Select a default Firebase project for this directory: (Use arrow keys)
❯ test-project (test-project)

Select "JavaScript" for this setup.

? What language would you like to use to write Cloud Functions? (Use arrow keys)
❯ JavaScript
TypeScript

Select "No" for the ESLint prompt.

? Do you want to use ESLint to catch probable bugs and enforce style? (y/N)

Select "Yes" to install the npm dependencies.

? Do you want to install dependencies with npm now? (Y/n)

The project setup is now complete. When you open the folder, you will see that the necessary files have been created.

Creating a Function

Open the generated functions/index.js file to review its contents. Uncommenting the sample code will reveal a test function.
In actual development, you'll replace this with your own logic. For this tutorial, we'll proceed to deployment as-is.

Deploying

Once your function is ready, let's deploy it.

firebase deploy

The deployment is complete when the following is displayed:

=== Deploying to 'test-project'...

i  deploying functions
i  functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i  functions: ensuring required API cloudbuild.googleapis.com is enabled...
✔  functions: required API cloudbuild.googleapis.com is enabled
✔  functions: required API cloudfunctions.googleapis.com is enabled
i  functions: preparing functions directory for uploading...
i  functions: packaged functions (27.77 KB) for uploading
✔  functions: functions folder uploaded successfully
i  functions: creating Node.js 10 function helloWorld(us-central1)...
✔  functions[helloWorld(us-central1)]: Successful create operation.
Function URL (helloWorld): https://us-central1-test-project.cloudfunctions.net/helloWorld

✔  Deploy complete!

Project Console: https://console.firebase.google.com/project/test-project/overview

Enter the generated URL into your browser. If you see the following message, it’s a success! Hello from Firebase!

応用編

In this section, we'll introduce some handy features worth knowing.

Running Locally Before Deployment

Deploying and checking the operation every time you modify the code can be tedious. In such cases, let's test it in a local environment.

firebase emulators:start

Changing the Location

The default is set to the Iowa region (us-central1). Since it's better to have it closer to home, we'll change it to the Tokyo region this time. Add .region('asia-northeast1') to your index.js file.

exports.helloWorld = functions
.region('asia-northeast1')
.https.onRequest((request, response) => {
 functions.logger.info("Hello logs!", {structuredData: true});
 response.send("Hello from Firebase!");
});

? Would you like to proceed with deletion? Selecting no will continue the rest of the deployments.

During deployment, you will be asked if you want to delete the function in us-central1 (Iowa). Select "Yes."

i  functions: deleting function helloWorld(us-central1)...
✔  functions[helloWorld(us-central1)]: Successful delete operation.
✔  functions[helloWorld(asia-northeast1)]: Successful create operation.
Function URL (helloWorld): https://asia-northeast1-test-project.cloudfunctions.net/helloWorld

✔  Deploy complete!

Project Console: https://console.firebase.google.com/project/test-project/overview

The deployment to the Tokyo region is now successful.

Conclusion

Our goal was to create a guide that covers those easy-to-overlook steps and hard-to-remember configuration details — a true "scratching where it itches" reference. We hope it proves useful to you.

Reference: Firebase Documentation

PREV
Vol.123SNS Communication Changing Amids…
NEXT
Vol.125Femtech and the well-being futur…

MORE FOR YOU