How to Secure Your Firebase Studio App
Firebase Studio lets you build full-stack apps powered by Firebase. While Firebase provides powerful security features, they must be configured correctly. This guide covers Security Rules, API key restrictions, Cloud Functions security, and authentication hardening.
Find security issues automatically before attackers do.
Follow These Steps
Write restrictive Firestore Security Rules
The default Firestore rules often allow all reads and writes. Replace them with rules that scope access to authenticated users and their own data.
// firestore.rules
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Users can only access their own document
match /users/{userId} {
allow read, update, delete: if request.auth != null && request.auth.uid == userId;
allow create: if request.auth != null && request.auth.uid == userId;
}
// Posts are readable by all authenticated users, writable by owner
match /posts/{postId} {
allow read: if request.auth != null;
allow create: if request.auth != null && request.resource.data.authorId == request.auth.uid;
allow update, delete: if request.auth != null && resource.data.authorId == request.auth.uid;
}
// Deny all other access
match /{document=**} {
allow read, write: if false;
}
}
}Secure Firebase Storage rules
Configure Storage rules so users can only access their own files. Prevent unrestricted uploads that could be used for abuse.
// storage.rules
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /users/{userId}/{allPaths=**} {
allow read: if request.auth != null && request.auth.uid == userId;
allow write: if request.auth != null
&& request.auth.uid == userId
&& request.resource.size < 5 * 1024 * 1024 // 5MB limit
&& request.resource.contentType.matches('image/.*'); // images only
}
}
}Always restrict file types and sizes in Storage rules. Without limits, attackers can upload large files or executable content.
Restrict your Firebase API key
While Firebase API keys are designed to be public, you should still restrict them to prevent abuse. Go to Google Cloud Console > Credentials and restrict the key to your domains and only the Firebase APIs you use.
// In Google Cloud Console > APIs & Services > Credentials
// Edit your Firebase API key and add:
// Application restrictions: HTTP referrers
// Website restrictions: yourdomain.com/*
// API restrictions: Only enable the Firebase APIs you actually useFirebase API keys are not secrets. Security comes from Security Rules, not key secrecy. But restricting them prevents quota abuse.
Secure Cloud Functions
If Firebase Studio generated Cloud Functions, ensure they validate input, check authentication, and handle errors properly.
import { onCall, HttpsError } from 'firebase-functions/v2/https'
import { z } from 'zod'
const CreateOrderSchema = z.object({
productId: z.string().min(1),
quantity: z.number().int().min(1).max(100)
})
export const createOrder = onCall(async (request) => {
// Check authentication
if (!request.auth) {
throw new HttpsError('unauthenticated', 'Must be logged in')
}
// Validate input
const parsed = CreateOrderSchema.safeParse(request.data)
if (!parsed.success) {
throw new HttpsError('invalid-argument', 'Invalid order data')
}
// Process order with validated data
return { orderId: '...' }
})Enable App Check
Firebase App Check helps protect your backend resources from abuse by verifying that requests come from your genuine app, not from bots or attackers.
// Initialize App Check in your frontend
import { initializeAppCheck, ReCaptchaV3Provider } from 'firebase/app-check'
const appCheck = initializeAppCheck(app, {
provider: new ReCaptchaV3Provider('your-recaptcha-site-key'),
isTokenAutoRefreshEnabled: true
})
// Enforce in Firestore rules
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}Configure authentication providers securely
Review which auth providers are enabled and configure them properly. Disable any you do not use, and enable email enumeration protection.
Go to Firebase Console > Authentication > Settings and enable Email enumeration protection. This prevents attackers from discovering which emails are registered.
Set up security monitoring
Enable Firebase Security Rules monitoring to detect and alert on suspicious access patterns. Use Cloud Logging to track authentication events.
// Enable detailed audit logging in Cloud Console
// Go to: Cloud Console > Logging > Log Router
// Create a sink for firestore.googleapis.com audit logs
// Monitor failed auth attempts
import { getAuth } from 'firebase-admin/auth'
// In a Cloud Function
export const onAuthFailure = functions.auth.user().beforeSignIn(async (user, context) => {
// Log and rate-limit sign-in attempts
console.log(`Sign-in attempt for ${user.email} from ${context.ipAddress}`)
})Scan and verify your security configuration
Deploy your secured Firebase Studio app and run a VAS scan to verify Security Rules are enforced and no misconfigurations remain.
Use the Firebase Emulator Suite to test Security Rules locally before deploying to production.
What You'll Achieve
Your Firebase Studio app now has restrictive Firestore and Storage Security Rules, API key restrictions, secured Cloud Functions with input validation, App Check enabled, and authentication hardened. Your Firebase backend is properly locked down.
Common Mistakes to Avoid
Mistake
Using allow read, write: if true in production
Fix
This allows anyone to read and write your entire database. Always scope rules to authenticated users and restrict to owned resources.
Mistake
Thinking Firebase API keys are secrets
Fix
Firebase API keys are designed to be public. Security comes from Security Rules, not from hiding the key. Focus on writing good rules instead.
Mistake
Not validating input in Cloud Functions
Fix
Cloud Functions receive untrusted input. Always validate with a schema library before processing. Check authentication on every callable function.
Mistake
Using Firestore Admin SDK in client code
Fix
The Admin SDK bypasses Security Rules. It should only be used in trusted server environments like Cloud Functions, never in client-side code.
Frequently Asked Questions
Are Firebase API keys a security risk?
No. Firebase API keys are designed to be public and are not secrets. They identify your project but do not grant access. Security is enforced by Firestore Security Rules and Storage Security Rules.
How do I test Security Rules before deploying?
Use the Firebase Emulator Suite. It lets you run and test Security Rules locally without affecting production. Write unit tests for your rules using the @firebase/rules-unit-testing package.
What is the most common Firebase security mistake?
Leaving Security Rules in test mode (allow read, write: if true). This gives anyone full access to your database. Always write restrictive rules before going to production.
Ready to Secure Your App?
VAS automatically scans your deployed app for the security issues covered in this guide. Get actionable results in minutes.
Start Security Scan