16. Google Cloud Integration: Beyond Firebase
Leveraging Google Cloud Services with Firebase
Firebase is built on Google Cloud, which means you can access a vast ecosystem of additional services. This module covers integrating Firebase with Cloud Run, Cloud SQL, Pub/Sub, and other Google Cloud services.
Google Cloud provides services beyond Firebase's scope. You can use Cloud Run for containerized applications, Cloud SQL for relational databases, and Pub/Sub for messaging. These services integrate seamlessly with Firebase. The shared authentication model allows you to use Firebase Auth across services. The billing is unified. Understanding Google Cloud integration is essential for building complex applications. Use Google Cloud for services not provided by Firebase. The integration is seamless and powerful.
Cloud Run with Firebase
Cloud Run is a managed serverless platform for containerized applications. It's ideal for APIs, web applications, and microservices. Cloud Run integrates with Firebase Authentication. You can use the Admin SDK to access Firebase services. Cloud Run automatically scales to zero when not in use. It's cost-effective for variable workloads. Use Cloud Run for complex backend logic that doesn't fit Cloud Functions. Cloud Run supports any language and framework. It's the next step beyond Cloud Functions for more complex applications.
# Dockerfile for Cloud Run FROM node:18-slim WORKDIR /usr/src/app COPY package*.json ./ RUN npm install COPY . . EXPOSE 8080 CMD ["node", "server.js"]
// server.js - Cloud Run with Firebase import express from 'express'; import { initializeApp } from 'firebase-admin/app'; import { getAuth } from 'firebase-admin/auth'; const app = express(); initializeApp(); app.use(express.json()); // Verify Firebase ID Token const authenticate = async (req, res, next) => { const idToken = req.headers.authorization?.split('Bearer ')[1]; if (!idToken) { return res.status(401).json({ error: 'Unauthorized' }); } try { const decodedToken = await getAuth().verifyIdToken(idToken); req.user = decodedToken; next(); } catch (error) { return res.status(401).json({ error: 'Invalid token' }); } }; app.get('/api/protected', authenticate, (req, res) => { res.json({ message: 'Protected data', user: req.user }); }); app.listen(8080);
Cloud SQL with Firebase
Cloud SQL provides managed PostgreSQL, MySQL, and SQL Server databases. It's ideal for applications with complex relational data requirements. Cloud SQL integrates with Firebase via the Admin SDK. You can use the SDK to access Cloud SQL data. The combination of Firestore (NoSQL) and Cloud SQL (relational) provides flexibility. Cloud SQL is more cost-effective than Firestore for large datasets. Use Cloud SQL for data that requires complex joins and reporting.
// Cloud Function with Cloud SQL import * as functions from 'firebase-functions'; import * as admin from 'firebase-admin'; import { Pool } from 'pg'; const pool = new Pool({ connectionString: functions.config().sql.connection_string, }); export const analyticsQuery = functions.https.onRequest(async (req, res) => { const client = await pool.connect(); try { const result = await client.query( 'SELECT * FROM analytics WHERE date > $1', [req.query.date] ); res.json(result.rows); } finally { client.release(); } });
Pub/Sub for Event-Driven Architecture
Cloud Pub/Sub provides reliable, scalable messaging between services. It's used for event-driven architectures. Pub/Sub decouples services, improving resilience and scalability. Firebase services can publish messages to Pub/Sub. Cloud Functions can subscribe to Pub/Sub topics. Use Pub/Sub for asynchronous processing and fan-out patterns. It's ideal for event-driven workflows.
// Cloud Function triggered by Pub/Sub message import * as functions from 'firebase-functions'; // This function triggers on Pub/Sub messages export const processUserEvent = functions.pubsub .topic('user-events') .onPublish(async (message) => { const data = JSON.parse(Buffer.from(message.data, 'base64').toString()); console.log('Processing user event:', data); // Process the event }); // Publishing from a Cloud Function const { PubSub } = require('@google-cloud/pubsub'); const pubsub = new PubSub(); export const createUser = functions.firestore .document('users/{userId}') .onCreate(async (snap) => { const userData = snap.data(); // Publish message to Pub/Sub const messageId = await pubsub .topic('user-events') .publishMessage({ data: Buffer.from(JSON.stringify({ type: 'user_created', userId: snap.id, email: userData.email, })), }); });
Knowledge Check
Ready to test your understanding of 16. Google Cloud Integration: Beyond Firebase?