Skip to main content
Version: 1.0.0

Introduction to Firebase Functions

What is Serverless and Why We Use It​

The Serverless Concept​

The term "serverless" doesn't mean there are no servers, but rather that server infrastructure management is completely abstracted from the developer. In a serverless architecture:

  • Zero Infrastructure Management: We don't need to worry about provisioning, scaling, or server maintenance
  • Pay-per-Use: You only pay for the actual execution time of functions
  • Automatic Scalability: The system scales automatically based on workload
  • Focus on Business Logic: Developers can concentrate exclusively on business logic

Role of Functions in Our Backend​

Firebase Functions represent the heart of our serverless backend, allowing us to:

When to Create a Firebase Function​

  1. Complex Backend Operations

    • Data processing that requires enhanced security
    • Operations requiring administrative privileges
    • Business logic that cannot be exposed to the client
  2. Integration with External Services

    • API calls to third-party services
    • Payment processing
    • Sending emails or push notifications
  3. Automatic Triggers

    • Response to database changes (onCreate, onUpdate, onDelete)
    • Scheduled operations (cron jobs)
    • Processing of files uploaded to Storage
  4. RESTful API Endpoints

    • Creation of public or private APIs
    • Data validation and sanitisation
    • Advanced authentication and authorisation

Supported Trigger Types​

  • HTTP Triggers: API endpoints accessible via HTTP requests
  • Firestore Triggers: Triggered by database changes
  • Authentication Triggers: Triggered by user registration/login events
  • Storage Triggers: Triggered by file upload/modification
  • Scheduled Functions: Programmed execution (cron jobs)

Firebase: Our Development Platform​

Firebase Overview​

Firebase is a Backend-as-a-Service (BaaS) platform by Google that provides an integrated suite of tools for application development. The main components we use in ARShades are:

1. Cloud Firestore​

  • Scalable NoSQL Database: Real-time data storage
  • Offline Synchronisation: Data is available even without connection
  • Powerful Queries: Support for complex queries and custom indices
  • Integrated Security: Document-level security rules

2. Firebase Functions​

  • Serverless Backend: Server-side code execution without managing infrastructure
  • Native Integration: Direct access to all Firebase services
  • Automatic Scaling: Automatic workload management

3. Firebase Authentication​

  • Complete User Management: Registration, login, password reset
  • Multiple Providers: Google, Facebook, email/password, phone
  • JWT Tokens: Secure authentication integrated with Firestore Rules

Why We Chose Firebase for ARShades​

1. Scalability​

  • Automatic Growth: The system scales automatically with business growth
  • Global Performance: Global CDN for optimal performance everywhere
  • Zero Downtime: Google's enterprise-grade infrastructure

2. Integrated Ecosystem​

  • Everything Interconnected: All services communicate natively with each other
  • Rapid Development: Less code to write, more out-of-the-box functionality
  • Excellent Documentation: Complete guides and active community

3. Development Speed​

  • Reduced Time-to-Market: Complex functionality implementable in hours/days rather than weeks
  • Rapid Prototyping: Ideal for MVP and fast iterations
  • Minimal Maintenance: Fewer bugs and infrastructure problems

Environment Management​

Production vs Staging​

We use two separate Firebase projects to ensure security and stability:

Production Environment​

  • Project: arshades-7e18a (ARSHADES)
  • Project Number: 1096373281553
  • Usage: Live application used by end users
  • Access: Limited to senior developers and admins only
  • Characteristics:
    • Real user data
    • Maximum stability required
    • Automatic backups active
    • Continuous monitoring

Staging Environment​

  • Project: arshadesstaging (ArshadesStaging)
  • Project Number: 251516419347
  • Usage: Testing, development and validation of new features
  • Access: All team developers
  • Characteristics:
    • Test data (never production)
    • Environment for experimentation
    • Periodic resets allowed
    • Configuration similar to production

⚠️ FUNDAMENTAL RULE: Never Use Production Data in Staging​

IMPORTANT: Never transfer real data from production environment to staging for reasons of:

  • Privacy: Protection of user data
  • GDPR Compliance: Adherence to European regulations
  • Security: Prevention of accidental leaks
  • Integrity: Avoiding contamination of test data

How to Switch Between Environments​

Using Firebase CLI​

# Login (if necessary)
firebase login

# View available projects
firebase projects:list

# Select staging environment
firebase use arshadesstaging

# Select production environment
firebase use arshades-7e18a

# Verify current project
firebase use

Configuration in Code​

To switch between environments in code, we use the constants.js file which manages the Firebase Admin SDK configuration:

// constants.js
const cors = require("cors")({ origin: true });
const { onRequest } = require("firebase-functions/v2/https");
const logger = require("firebase-functions/logger");
const nodemailer = require("nodemailer");
const admin = require("firebase-admin");

// View available projects
// firebase projects:list

// Select staging environment
// firebase use arshadesstaging

// Select production environment
// firebase use arshades-7e18a

// Configuration for staging environment
const serviceAccount = require("../service/arshadesstaging-firebase-adminsdk-qyt0v-e81a3b2c01.json");
// Configuration for production environment
// const serviceAccount = require('../service/arshades-7e18a-firebase-adminsdk-k4imz-f473ca1e3d.json');

if (!admin.apps.length) {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
// URL for staging environment
databaseURL: "https://arshadesstaging.firebaseio.com",
// URL for production environment
// databaseURL: "https://arshades-7e18a.firebaseio.com",
});
}

module.exports = {
admin: admin,
db: admin.firestore(),
};

To change environment:

  1. From Staging to Production: Comment out staging lines and uncomment production ones
  2. From Production to Staging: Comment out production lines and uncomment staging ones
  3. Execute deployment: firebase deploy --only functions

⚠️ CAUTION: Always ensure you're on the correct project before deployment:

firebase use  # Verify current project
firebase use arshades-7e18a # For production
firebase use arshadesstaging # For staging