Skip to main content
RapidDev - Software Development Agency
lovable-integrationsEdge Function Integration

How to Integrate Lovable with Firebase

Connect Firebase to your Lovable app by creating an Edge Function that calls Firebase's REST API using a service account. Store your service account JSON credentials in Cloud Secrets. This gives you access to Firestore, Firebase Auth, and Cloud Storage from any Lovable app. Use this when your project requires Firebase's full platform rather than just Supabase's PostgreSQL backend.

What you'll learn

  • How to create a Firebase service account and store its credentials in Lovable Cloud Secrets
  • How to write Edge Functions that call Firestore, Firebase Auth, and Cloud Storage REST APIs
  • How to perform CRUD operations on Firestore collections from a Lovable frontend
  • How to handle Firebase Auth token verification in a Deno Edge Function
  • When to use Firebase versus Lovable's built-in Supabase backend
Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Intermediate13 min read45 minutesDatabaseMarch 2026RapidDev Engineering Team
TL;DR

Connect Firebase to your Lovable app by creating an Edge Function that calls Firebase's REST API using a service account. Store your service account JSON credentials in Cloud Secrets. This gives you access to Firestore, Firebase Auth, and Cloud Storage from any Lovable app. Use this when your project requires Firebase's full platform rather than just Supabase's PostgreSQL backend.

Connect Firebase's Full Platform to Your Lovable App

Firebase is not one of Lovable's 17 official shared connectors, which means there is no chat-driven setup wizard. But Firebase is entirely accessible through Lovable's Edge Function system — the Firebase Admin REST API accepts standard HTTPS requests, and a Deno Edge Function can make those requests securely using a service account JWT.

The key difference from Lovable's native Supabase backend is the investment required. With Supabase built-in, Lovable's AI generates schemas, creates RLS policies, and wires real-time subscriptions automatically. With Firebase, you describe your Firestore collections and document structure explicitly, and Lovable generates the Edge Function code to interact with them. This is manageable but requires more upfront effort.

The use case for choosing Firebase over Supabase built-in is clear: if you have an existing Firebase project with data, users, and Cloud Functions already in production, or if your team has Firebase expertise and prefers its document model and global CDN. Firebase's Firestore is particularly strong for hierarchical data like chat messages, user activity feeds, and nested documents that don't map cleanly to PostgreSQL's relational model.

Integration method

Edge Function Integration

Firebase connects to Lovable through Edge Functions that call the Firebase Admin REST API using a service account. Your service account credentials are stored in Cloud Secrets, and all Firestore reads, Auth operations, and Storage calls route through the Edge Function so credentials stay server-side.

Prerequisites

  • A Lovable account with a project open and Lovable Cloud enabled
  • A Firebase project at console.firebase.google.com with Firestore, Auth, or Storage enabled
  • A Firebase service account JSON file downloaded from Firebase Console → Project Settings → Service Accounts
  • Basic understanding of your Firestore collection structure — collection names and document field names
  • If using Firebase Auth on the client, the Firebase JS SDK package or a CDN script for your Lovable frontend

Step-by-step guide

1

Create and Download a Firebase Service Account

A service account gives your Edge Function administrative access to your Firebase project. To create one, open the Firebase Console at console.firebase.google.com, select your project, and click the gear icon next to 'Project Overview' → 'Project settings'. Navigate to the 'Service accounts' tab. You'll see a section labeled 'Firebase Admin SDK' with code snippets — ignore those for now. Click 'Generate new private key', then 'Generate key' in the confirmation dialog. Firebase downloads a JSON file to your computer. This file contains your project ID, a private key, and a client email — all the credentials needed to authenticate as a service admin. Keep this file secure and never commit it to GitHub or share it in chat. The JSON file looks like: { "type": "service_account", "project_id": "your-project", "private_key_id": "...", "private_key": "-----BEGIN RSA PRIVATE KEY-----\n...", "client_email": "firebase-adminsdk-...@your-project.iam.gserviceaccount.com", ... }. You'll paste the entire contents of this JSON file into a single Lovable secret in the next step.

Pro tip: Grant only the permissions Firebase needs. By default, service accounts get editor access to the whole project. For more secure setups, use the Google Cloud Console IAM page to restrict the service account to only the Firebase services you need.

Expected result: A JSON file is downloaded to your computer containing the service account credentials for your Firebase project.

2

Store Firebase Credentials in Cloud Secrets

In Lovable, click the '+' button next to the Preview panel to open the Cloud tab, then navigate to Secrets. You need to add multiple secrets for Firebase: the full service account JSON, and individual values the Edge Function will need. Add the following secrets: - FIREBASE_SERVICE_ACCOUNT_JSON: paste the entire JSON file contents as a single-line string (you may need to minify it or ensure it pastes without line breaks) - FIREBASE_PROJECT_ID: your Firebase project ID (e.g., my-app-12345) - FIREBASE_DATABASE_URL: your Realtime Database URL if using RTDB (e.g., https://my-app-12345-default-rtdb.firebaseio.com) — omit if using only Firestore Storing the full service account JSON as a single secret is the recommended approach for Deno Edge Functions. The Edge Function will parse it with JSON.parse(Deno.env.get('FIREBASE_SERVICE_ACCOUNT_JSON')) to extract the credentials needed for JWT signing. Lovable's security system actively blocks approximately 1,200 private keys from being hardcoded into code per day. Even so, never paste service account JSON in the chat panel — on free tier, chat history is publicly visible and pasted secrets are recoverable from commit history.

Pro tip: If your service account JSON paste fails due to line breaks or special characters, convert it to a single-line string first: open the file in a text editor, select all, copy, and use an online JSON minifier to remove whitespace before pasting into the Secrets panel.

Expected result: FIREBASE_SERVICE_ACCOUNT_JSON and FIREBASE_PROJECT_ID appear in your Cloud Secrets list. The Edge Functions in the next steps can access them via Deno.env.get().

3

Create the Firestore Query Edge Function

Now create the core Edge Function that proxies Firestore operations. Ask Lovable to generate an Edge Function at supabase/functions/firebase-firestore/index.ts. This function will authenticate with Firebase using a signed JWT generated from the service account credentials, then call Firestore's REST API. Firestore's REST API base URL is: https://firestore.googleapis.com/v1/projects/{PROJECT_ID}/databases/(default)/documents/. All read and write operations use standard HTTP methods: GET for reading documents and collections, POST for creating documents, PATCH for updating, and DELETE for deleting. The authentication flow requires generating a Google OAuth2 access token by signing a JWT with the service account's private key — the Edge Function cannot use the Firebase Admin Node.js SDK directly because it is not compatible with Deno's runtime. Instead, Lovable generates code that uses the Web Crypto API (available natively in Deno) to sign the JWT and exchange it for an access token from Google's OAuth endpoint. This is more code than the Node.js SDK pattern but works reliably in Deno. The Edge Function should accept a collection name, document ID (optional), and operation type, then construct the appropriate Firestore REST call and return the response.

Lovable Prompt

Create an Edge Function called firebase-firestore at supabase/functions/firebase-firestore/index.ts. It should use the service account credentials from FIREBASE_SERVICE_ACCOUNT_JSON to generate a Google OAuth2 access token using the Web Crypto API for JWT signing (not the Firebase Admin SDK — it's not Deno-compatible). The function should accept POST requests with: operation (get, list, create, update, delete), collection (string), docId (optional string), data (optional object for create/update), and pageSize (optional number, default 20). Use the Firestore REST API at https://firestore.googleapis.com/v1/projects/{projectId}/databases/(default)/documents. Include CORS headers and proper error handling.

Paste this in Lovable chat

Expected result: Lovable creates supabase/functions/firebase-firestore/index.ts with JWT generation code and Firestore REST API calls. The function appears in Cloud → Edge Functions.

4

Build Frontend Components That Read and Write Firestore Data

With the Edge Function deployed, open the Lovable chat and describe the UI components you want. Provide your Firestore collection structure so Lovable generates accurate field references. A useful prompt format is: 'My Firestore collection users has documents with fields: displayName (string), email (string), plan (string), createdAt (timestamp). Using the firebase-firestore Edge Function, build a user list page with search by name and filter by plan.' Lovable generates React components that fetch from your Edge Function using the standard Supabase functions URL pattern: https://[project-ref].supabase.co/functions/v1/firebase-firestore. The fetch call includes a JSON body specifying the operation, collection, and any filters. Loading states, error handling, and data display are all generated automatically. For real-time updates (Firestore's most popular feature), note that the REST API does not support WebSocket streaming. The Edge Function pattern gives you request/response queries only. If you need real-time Firestore updates in your Lovable app, consider adding the Firebase JS SDK directly to your frontend and using it only for Firestore's onSnapshot listener, while keeping all write operations routed through the Edge Function for security.

Lovable Prompt

Using the firebase-firestore Edge Function, build a task management page for my app. My Firestore collection is called tasks with documents having fields: title (string), description (string), assignee (string), status (string: 'todo', 'in-progress', 'done'), dueDate (string), createdAt (timestamp). Build: a Kanban board showing tasks in three columns by status, the ability to create a new task with a form, and drag-and-drop to move tasks between status columns that updates Firestore. Use shadcn/ui Card components for task cards.

Paste this in Lovable chat

Pro tip: Firestore document IDs from the REST API are returned in the document's name field as a full path like projects/myproject/databases/(default)/documents/tasks/abc123. Extract just the document ID with name.split('/').pop() in your Edge Function before returning the response.

Expected result: A Kanban board appears in your Lovable app with tasks loaded from your Firestore collection. Creating and moving tasks triggers updates that persist in the Firebase Console.

5

Verify Firebase Auth Tokens in Edge Functions

If your Lovable app uses Firebase Authentication on the client (with the Firebase JS SDK), you can verify those ID tokens in your Edge Functions to authenticate requests. This is important for ensuring only the right users can access or modify specific Firestore documents. The Firebase ID token verification flow works by calling Google's tokeninfo endpoint or by validating the JWT signature locally using Google's public keys. For Lovable Edge Functions, the practical approach is to send the Firebase ID token as a Bearer token in the Authorization header from the frontend, then have the Edge Function validate it by calling Firebase's token exchange API. This step is optional if your app does not use Firebase Authentication — but if it does, adding token verification ensures that unauthenticated callers cannot invoke your Firestore Edge Function and read or modify data. Ask Lovable to add an authentication middleware that extracts and verifies the Firebase token before processing any Firestore request. For complex authentication scenarios involving custom claims, role-based access, or integration with Firebase Security Rules, RapidDev's team can help design the right verification pattern for your specific use case.

Lovable Prompt

Update my firebase-firestore Edge Function to verify Firebase Authentication. The frontend sends a Firebase ID token as a Bearer token in the Authorization header. Add a verification step that calls https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com to get Google's public keys, validates the JWT signature and expiry, and extracts the user's uid. Reject requests with a 401 response if the token is missing or invalid. Pass the verified uid to the Firestore query so I can filter documents by the requesting user's ID.

Paste this in Lovable chat

Expected result: Your Edge Function rejects unauthenticated requests with a 401 response. Authenticated users from your Lovable app can query Firestore and only see documents matching their Firebase uid.

Common use cases

Build a Lovable frontend for an existing Firebase app

Your app already runs on Firebase with Firestore data, authenticated users, and Cloud Functions. You want to rebuild or extend the frontend using Lovable's AI while keeping Firebase as the backend. The Edge Function proxy connects your new Lovable UI to your existing Firebase project without migrating any data.

Lovable Prompt

I have an existing Firebase project with Firestore collections: users (documents with name, email, role fields), posts (documents with authorId, title, content, createdAt, published fields), and comments (sub-collection under posts with authorId, body, createdAt). I've stored my service account credentials in Cloud Secrets as FIREBASE_SERVICE_ACCOUNT_JSON. Create Edge Functions for listing published posts, getting a single post with its comments, and creating a new post. Then build a blog frontend using these functions.

Copy this prompt to try it in Lovable

Sync user authentication between Firebase Auth and Lovable

Your existing users authenticate with Firebase Auth. You want to use Firebase ID tokens to identify users in your Lovable app, verify those tokens server-side in an Edge Function, and access user-specific Firestore data based on the verified identity.

Lovable Prompt

My app uses Firebase Authentication. Users sign in on the client using the Firebase JS SDK and receive an ID token. Create a Lovable Edge Function called verify-firebase-token that accepts an Authorization header with a Firebase ID token, verifies it against the Firebase Auth REST API using my service account credentials (stored as FIREBASE_SERVICE_ACCOUNT_JSON), and returns the decoded user claims including uid, email, and custom claims. Use this function to protect all other Firebase Edge Functions.

Copy this prompt to try it in Lovable

Store and serve user-uploaded files via Firebase Cloud Storage

Your Lovable app needs file upload functionality and you want to store files in Firebase Cloud Storage rather than Lovable's built-in storage. An Edge Function handles the upload by calling Firebase Storage's REST API and returns a download URL.

Lovable Prompt

I need to store user profile photos in Firebase Cloud Storage. I have a storage bucket called my-app.appspot.com. Using my service account credentials stored as FIREBASE_SERVICE_ACCOUNT_JSON, create an Edge Function called upload-to-firebase-storage that accepts a file upload, stores it under users/{userId}/profile-photo, and returns the Firebase Storage download URL. Then add a profile photo upload component to my app's settings page.

Copy this prompt to try it in Lovable

Troubleshooting

Edge Function returns '403 Forbidden' or 'PERMISSION_DENIED' when calling Firestore REST API

Cause: The service account does not have permission to access Firestore, or Firestore Security Rules are blocking the operation even though you're using a service account.

Solution: Service account access bypasses Firestore Security Rules by default when using the Firebase Admin SDK. However, the REST API with an OAuth2 token from a service account also bypasses client-side security rules. If you're still getting 403 errors, check that your service account has the 'Firebase Admin' or 'Cloud Datastore User' role in Google Cloud Console IAM. Open console.cloud.google.com → IAM & Admin → IAM, find the service account email, and verify its roles. Also ensure you're sending the access token in the Authorization header as 'Bearer {token}', not as a query parameter.

JWT generation fails with 'invalid key format' or 'CryptoKey error' in the Edge Function

Cause: The service account private key stored in FIREBASE_SERVICE_ACCOUNT_JSON has escaped newline characters (\n as literal text) rather than actual newline characters, which breaks the Web Crypto API's key import.

Solution: When parsing the service account JSON in your Edge Function, replace escaped newline sequences with real newlines before using the private key. Add this transformation when extracting the private key from the parsed JSON.

typescript
1const serviceAccount = JSON.parse(Deno.env.get("FIREBASE_SERVICE_ACCOUNT_JSON") || "{}");
2// Fix escaped newlines from environment variable storage
3const privateKey = serviceAccount.private_key.replace(/\\n/g, "\n");

Firestore returns 'document not found' even though the document exists in the Firebase Console

Cause: The collection or document path in the REST API URL is incorrectly formatted, or the document ID contains special characters that need URL encoding.

Solution: Firestore REST API paths are case-sensitive and must exactly match collection and document names. The URL format is: .../documents/{collection}/{documentId}. Verify the exact spelling in the Firebase Console. If document IDs contain slashes, spaces, or special characters, URL-encode them with encodeURIComponent(). Also ensure you're using the correct Firebase project ID — check FIREBASE_PROJECT_ID in Cloud Secrets matches the project ID shown in Firebase Console → Project Settings.

Firebase Auth token verification returns 'Token expired' for tokens that were just issued

Cause: There is a clock skew between your Edge Function's server time and Google's authentication servers, or the token was generated with a very short expiry.

Solution: Firebase ID tokens expire after one hour by default. If tokens are expiring sooner, the Firebase JS SDK on your frontend may not be refreshing them properly. Add token refresh logic to your frontend: listen to Firebase's onAuthStateChanged event, and when a user is active, call user.getIdToken(true) to force-refresh the token before making Edge Function calls. In the Edge Function, also add a 5-minute leeway to the expiry check to handle minor clock differences.

Best practices

  • Store the entire Firebase service account JSON as a single Cloud Secret — never split it across multiple secrets or hardcode any part in Edge Function code
  • Replace escaped newline characters (\n) in the private key after parsing from environment variables, as storage encoding can corrupt the key format
  • Always verify Firebase ID tokens server-side in your Edge Functions before executing Firestore operations on user-specific data
  • Cache Google OAuth2 access tokens for their full 3600-second validity period instead of generating a new token per request — this significantly reduces latency
  • Use Firestore document IDs in the response by extracting them from the name field path (name.split('/').pop()) rather than relying on frontend-generated IDs
  • Route all Firestore write operations through Edge Functions rather than calling the Firebase REST API directly from your React frontend — this keeps credentials server-side
  • Use Firebase Console → Firestore → Rules to define security rules as a backup layer, even though service account calls bypass them — it protects you if direct client access is ever accidentally enabled
  • Monitor Edge Function execution times in Cloud → Logs — JWT generation and Google OAuth token exchange add latency; if responses exceed 5 seconds, implement token caching

Alternatives

Frequently asked questions

Can I use the Firebase JavaScript SDK directly in my Lovable React components?

Yes, you can install the Firebase JS SDK (firebase package) in your Lovable project and call Firestore or Auth directly from the frontend. However, this should only be used for operations that are safe with client-side Firebase Security Rules and the anon/user credentials — never for Admin operations. Sensitive operations like reading other users' data or bypassing security rules must always go through Edge Functions with a service account.

Does Firebase real-time data sync work with this Edge Function pattern?

Real-time Firestore listeners (onSnapshot) do not work through Edge Functions because the REST API does not support WebSocket streaming. For real-time features, install the Firebase JS SDK in your React components and use onSnapshot directly on the client. Use Edge Functions only for write operations and queries that need admin privileges. This hybrid approach is common and fully supported.

How is this different from the firebase-cloud-messaging integration?

This integration covers Firebase's full platform — Firestore database, Authentication, and Cloud Storage. The Firebase Cloud Messaging integration focuses exclusively on sending push notifications to mobile and web clients. If you need both database operations and push notifications, use this full platform integration as your base and add FCM-specific Edge Functions for notification sending.

What happens if my Firebase service account key is compromised?

Immediately revoke the compromised key in Firebase Console → Project Settings → Service Accounts by clicking the three dots next to the key and selecting 'Delete key'. Generate a new key, update the FIREBASE_SERVICE_ACCOUNT_JSON secret in Lovable's Cloud Secrets panel, and redeploy your Edge Functions. All existing tokens generated from the revoked key become invalid within minutes.

Can Lovable's AI help me design my Firestore schema?

Lovable's AI can suggest Firestore collection structures when you describe your app's data requirements. While it cannot automatically create Firestore collections the way it creates Supabase tables, you can ask it to recommend a document structure and then create those collections manually in the Firebase Console before building the Edge Functions. The AI is particularly helpful at translating relational schemas into Firestore's nested collection/sub-collection model.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Need help with your project?

Our experts have built 600+ apps and can accelerate your development. Book a free consultation — no strings attached.

Book a free consultation

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.