npm i -g firebase-tools
or
yarn global add firebase-tools
In order to start with firebase, we need to login in google, so run the follwoing command to login
firebase login
It will output a link, click/open the link and select your google account in browser to use with this firebase project.
Note: If you are already logged in but want to switch account, just run
firebase logout
and thenfirebase login
to select another account.
2.1.1: Navigate to your existing project's directory / Create a new directory
2.1.2: To initialize firebase run the following command
firebase init
Go through the wizard and select Functions: Configure and deploy Cloud Functions
, your project
, and javascript
as functions language.
2.1.3: Navigate to functions
directory
cd functions
2.2.1: Install cors to enable it
npm i cors --save
or
yarn add cors
2.2.2: Sample function body to start with
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const cors = require("cors")({ origin: true });
admin.initializeApp();
exports.myCloudFunction1 = functions.https.onRequest((request, response) => {
cors(request, response, () => {
return new Promise(resolve => {
// Your code goes here
// Once data prepared, send response
response.status(200).send({
error: false,
data: 'Executed!'
})
resolve(true);
});
})
.catch(err => {
res.status(401).send(err);
});
});
2.2.3: Sample function body with firestore
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const cors = require("cors")({ origin: true });
admin.initializeApp();
exports.getAllProducts = functions.https.onRequest((request, response) => {
cors(request, response, () => {
return new Promise(resolve => {
admin
.firestore()
.collection("products")
.get()
.then(querySnapshot => {
const products = [];
querySnapshot.forEach(doc => {
products.push({
id: doc.id,
name: doc.data()["name"]
});
});
response.status(200).send({
error: false,
data: products
})
resolve(true);
});
})
.catch(err => {
res.status(401).send(err);
});
});
});
firebase serve --only functions
firebase deploy --only functions