How to create, deploy and work with firebase function
In this article iam gonna explain you how you can create firebase function, deploy and work with firebase function
Step 1: Create a Firebase Project or you can skip this step of you have already created your firebase project
-
Go to https://firebase.google.com and click on Get Started
-
Proceed to click on Create a project.
-
Enter a project name and check yes if you wish to add analytics to your project.
-
Wait for the project to be created.
Step 2 Install firebase tools and initialize firebase function
- Run below command to install firebase tools globally
npm install -g firebase-tools
- Initialize firebase function
firebase login
firebase init
- Select Functions option in below step
$ firebase init
> ? Which Firebase features do you want to set up for this directory? Press Space to select features, then Enter to confirm your choices
. (Press <space> to select, <a> to toggle all, <i> to invert selection, and <enter> to proceed)
❯◯ Realtime Database: Configure a security rules file for Realtime Database and (optionally) provision default instance
◯ Firestore: Configure security rules and indexes files for Firestore
◯ Functions: Configure a Cloud Functions directory and its files
◯ Hosting: Configure files for Firebase Hosting and (optionally) set up GitHub Action deploys
◯ Hosting: Set up GitHub Action deploys
◯ Storage: Configure a security rules file for Cloud Storage
◯ Emulators: Set up local emulators for Firebase products
(Move up and down to reveal more choices)
- Select Language
? What language would you like to use to write Cloud Functions? (Use arrow keys)
❯ JavaScript
TypeScript
- Install packages
? What language would you like to use to write Cloud Functions? JavaScript
? Do you want to use ESLint to catch probable bugs and enforce style? No
✔ Wrote functions/package.json
✔ Wrote functions/index.js
✔ Wrote functions/.gitignore
? Do you want to install dependencies with npm now? (Y/n) Yes
Step 3 Write your function inside functions/index.js file and deploy
Once function initialized and created you will see a folder functions and inside that folder you will have a main file named as index.js where you can define your function
A example function has already been created for you just un comment that
const functions = require("firebase-functions");
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.helloWorld = functions.https.onRequest((request, response) => {
functions.logger.info("Hello logs!", { structuredData: true });
response.send("Hello from Firebase!");
});
- Deploy your function using below command
firebase deploy --only functions
- Once deployed you can access the function just replace the project id with your firebase project id
https://us-central1-<project-id>.cloudfunctions.net/helloWorld