Cloud Functions
Advanced
Topic 12 of 18
Cloud Functions
Firebase Cloud Functions allow you to run backend code in response to events or direct calls, without managing your own server, making them ideal for secure operations React Native apps should not perform directly.
Installing Cloud Functions
bash
npm install @react-native-firebase/functions
Writing a Callable Cloud Function
javascript
// functions/index.js (backend)
const functions = require('firebase-functions');
exports.calculateOrderTotal = functions.https.onCall((data, context) => {
const total = data.items.reduce((sum, item) => sum + item.price * item.quantity, 0);
return { total };
});
Calling a Function from React Native
javascript
import functions from '@react-native-firebase/functions';
const calculateTotal = functions().httpsCallable('calculateOrderTotal');
const result = await calculateTotal({ items: cartItems });
console.log(result.data.total);
Handling Function Errors
javascript
try {
await calculateTotal({ items: cartItems });
} catch (error) {
console.log(error.code, error.message);
}
Why Use Cloud Functions
Cloud Functions are ideal for sensitive operations, such as processing payments, validating data, or accessing third-party APIs with secret keys, that should never run directly on the client for security reasons.
Triggering Functions from Firestore Events
javascript
exports.onNewOrder = functions.firestore
.document('orders/{orderId}')
.onCreate((snap, context) => {
// Send notification, update inventory, etc.
});
Conclusion
Firebase Cloud Functions provide a secure, serverless backend for React Native applications, handling sensitive logic and event-driven automation without requiring you to manage dedicated server infrastructure.