|
| 1 | +# Firebase Functions Context (SDK 6.0.0+) |
| 2 | + |
| 3 | +Always use v2 functions for new development. Use v1 only for Analytics, basic Auth, and Test Lab triggers. |
| 4 | + |
| 5 | +For SDK versions before 6.0.0, add `/v2` to import paths (e.g., `firebase-functions/v2/https`). |
| 6 | + |
| 7 | +## Function Imports (SDK 6.0.0+) |
| 8 | + |
| 9 | +<example> |
| 10 | +```typescript |
| 11 | +// HTTPS functions |
| 12 | +import {onRequest, onCall} from 'firebase-functions/https'; |
| 13 | + |
| 14 | +// Firestore triggers |
| 15 | +import {onDocumentCreated, onDocumentUpdated, onDocumentDeleted} from 'firebase-functions/firestore'; |
| 16 | + |
| 17 | +// RTDB triggers |
| 18 | +import {onValueCreated, onValueWritten, onValueUpdated, onValueDeleted} from 'firebase-functions/database'; |
| 19 | + |
| 20 | +// Scheduled functions |
| 21 | +import {onSchedule} from 'firebase-functions/scheduler'; |
| 22 | + |
| 23 | +// Storage triggers |
| 24 | +import {onObjectFinalized, onObjectDeleted} from 'firebase-functions/storage'; |
| 25 | + |
| 26 | +// Pub/Sub triggers |
| 27 | +import {onMessagePublished} from 'firebase-functions/pubsub'; |
| 28 | + |
| 29 | +// Blocking Auth triggers |
| 30 | +import {beforeUserCreated, beforeUserSignedIn} from 'firebase-functions/identity'; |
| 31 | + |
| 32 | +// Test Lab triggers |
| 33 | +import {onTestMatrixCompleted} from 'firebase-functions/testLab'; |
| 34 | + |
| 35 | +// Deferred initialization |
| 36 | +import {onInit} from 'firebase-functions'; |
| 37 | + |
| 38 | +// Structured logging |
| 39 | +import {logger} from 'firebase-functions'; |
| 40 | + |
| 41 | +// Configuration |
| 42 | +import {defineString, defineInt, defineSecret} from 'firebase-functions/params'; |
| 43 | +import * as params from 'firebase-functions/params'; |
| 44 | + |
| 45 | +// Note: For SDK versions before 6.0.0, add /v2 to import paths: |
| 46 | +// import {onRequest} from 'firebase-functions/v2/https'; |
| 47 | + |
| 48 | +```` |
| 49 | +</example> |
| 50 | + |
| 51 | +## v1 Functions (Analytics & Basic Auth Only) |
| 52 | + |
| 53 | +<example> |
| 54 | +```typescript |
| 55 | +// Use v1 ONLY for these triggers |
| 56 | +import * as functionsV1 from 'firebase-functions/v1'; |
| 57 | +import {logger} from 'firebase-functions'; |
| 58 | +
|
| 59 | +// Analytics triggers (v1 only) |
| 60 | +export const onPurchase = functionsV1.analytics.event('purchase').onLog((event) => { |
| 61 | + logger.info('Purchase event', { |
| 62 | + value: event.params?.value, |
| 63 | + currency: event.params?.currency |
| 64 | + }); |
| 65 | +}); |
| 66 | +
|
| 67 | +// Basic Auth triggers (v1 only) |
| 68 | +export const onUserCreate = functionsV1.auth.user().onCreate((user) => { |
| 69 | + logger.info('User created', { uid: user.uid, email: user.email }); |
| 70 | + // Initialize user profile... |
| 71 | +}); |
| 72 | +
|
| 73 | +export const onUserDelete = functionsV1.auth.user().onDelete((user) => { |
| 74 | + logger.info('User deleted', { uid: user.uid }); |
| 75 | + // Cleanup user data... |
| 76 | +}); |
| 77 | +```` |
| 78 | +
|
| 79 | +</example> |
| 80 | +
|
| 81 | +## Environment Configuration |
| 82 | +
|
| 83 | +<example> |
| 84 | +```typescript |
| 85 | +import {defineString, defineInt, defineSecret} from 'firebase-functions/params'; |
| 86 | +import * as params from 'firebase-functions/params'; |
| 87 | +import {onRequest} from 'firebase-functions/https'; |
| 88 | +import {logger} from 'firebase-functions'; |
| 89 | + |
| 90 | +// Built-in params available automatically |
| 91 | +const projectId = params.projectID; |
| 92 | +const databaseUrl = params.databaseURL; |
| 93 | +const bucket = params.storageBucket; |
| 94 | +const gcpProject = params.gcloudProject; |
| 95 | + |
| 96 | +// Custom params |
| 97 | +const apiUrl = defineString('API_URL', { |
| 98 | + default: 'https://api.example.com' |
| 99 | +}); |
| 100 | + |
| 101 | +const environment = defineString('ENVIRONMENT', { |
| 102 | + default: 'dev' |
| 103 | +}); |
| 104 | + |
| 105 | +const apiKey = defineSecret('STRIPE_KEY'); |
| 106 | + |
| 107 | +// Using params directly in runtime configuration |
| 108 | +export const processPayment = onRequest({ |
| 109 | + secrets: [apiKey], |
| 110 | + memory: defineString('PAYMENT_MEMORY', { default: '1GiB' }), |
| 111 | + minInstances: environment.equals('production').thenElse(5, 0), |
| 112 | + maxInstances: environment.equals('production').thenElse(1000, 10) |
| 113 | +}, async (req, res) => { |
| 114 | + logger.info('Processing payment', { |
| 115 | + project: projectId.value(), |
| 116 | + bucket: bucket.value(), |
| 117 | + env: environment.value() |
| 118 | + }); |
| 119 | + |
| 120 | + const key = apiKey.value(); |
| 121 | + const url = apiUrl.value(); |
| 122 | + // Process payment... |
| 123 | +}); |
| 124 | + |
| 125 | +```` |
| 126 | +</example> |
| 127 | + |
| 128 | +## Deferred Initialization |
| 129 | + |
| 130 | +<example> |
| 131 | +```typescript |
| 132 | +import {onInit} from 'firebase-functions'; |
| 133 | +import {onRequest} from 'firebase-functions/https'; |
| 134 | +
|
| 135 | +let heavyClient: HeavySDK; |
| 136 | +
|
| 137 | +onInit(async () => { |
| 138 | + const {HeavySDK} = await import('./lib/heavy-sdk'); |
| 139 | + heavyClient = new HeavySDK({ |
| 140 | + // Expensive initialization... |
| 141 | + }); |
| 142 | +}); |
| 143 | +
|
| 144 | +export const useHeavyClient = onRequest(async (req, res) => { |
| 145 | + const result = await heavyClient.process(req.body); |
| 146 | + res.json(result); |
| 147 | +}); |
| 148 | +```` |
| 149 | +
|
| 150 | +</example> |
| 151 | +
|
| 152 | +## Structured Logging |
| 153 | +
|
| 154 | +<example> |
| 155 | +```typescript |
| 156 | +import {logger} from 'firebase-functions'; |
| 157 | +import {onRequest} from 'firebase-functions/https'; |
| 158 | + |
| 159 | +interface OrderRequest { |
| 160 | + orderId: string; |
| 161 | + userId: string; |
| 162 | + amount: number; |
| 163 | +} |
| 164 | + |
| 165 | +export const processOrder = onRequest(async (req, res) => { |
| 166 | + const {orderId, userId, amount} = req.body as OrderRequest; |
| 167 | + |
| 168 | + logger.info("Processing order", { |
| 169 | + orderId, |
| 170 | + userId, |
| 171 | + amount |
| 172 | + }); |
| 173 | + |
| 174 | + try { |
| 175 | + // Process... |
| 176 | + logger.log("Order complete", { orderId }); |
| 177 | + res.json({ success: true }); |
| 178 | + } catch (error) { |
| 179 | + logger.error("Order failed", { |
| 180 | + orderId, |
| 181 | + error: error instanceof Error ? error.message : 'Unknown error', |
| 182 | + stack: error instanceof Error ? error.stack : undefined |
| 183 | + }); |
| 184 | + res.status(500).json({ error: "Processing failed" }); |
| 185 | + } |
| 186 | +}); |
| 187 | + |
| 188 | +```` |
| 189 | +</example> |
| 190 | + |
| 191 | +## Development Commands |
| 192 | + |
| 193 | +<example> |
| 194 | +```bash |
| 195 | +# TypeScript development |
| 196 | +cd functions |
| 197 | +npm install |
| 198 | +npm run build # Compile TypeScript |
| 199 | +
|
| 200 | +# Local development |
| 201 | +
|
| 202 | +firebase emulators:start --only functions |
| 203 | +
|
| 204 | +# Testing functions |
| 205 | +
|
| 206 | +npm test # Run unit tests |
| 207 | +npm run serve # TypeScript watch + emulators |
| 208 | +
|
| 209 | +# Deployment |
| 210 | +
|
| 211 | +firebase deploy --only functions |
| 212 | +firebase deploy --only functions:api,functions:onUserCreate |
| 213 | +
|
| 214 | +# Debugging |
| 215 | +
|
| 216 | +firebase functions:log |
| 217 | +firebase functions:log --only api --lines=50 |
| 218 | +
|
| 219 | +```` |
| 220 | +
|
| 221 | +</example> |
0 commit comments