Integrate Firebase Authentication with Lovable by installing the Firebase SDK, initializing it with your project config stored in Cloud tab > Secrets, and creating an AuthProvider component that listens for auth state changes. Firebase Auth supports email/password, Google sign-in, and magic links. Store the Firebase config values as VITE_ environment variables and use onAuthStateChanged to persist sessions across page refreshes.
Why Firebase Auth requires manual setup in Lovable
Lovable's built-in authentication uses Supabase, which is deeply integrated into Lovable Cloud. Firebase Authentication is a separate service that requires manual configuration. You need to create a Firebase project, obtain the SDK config values, store them as environment variables, install the Firebase SDK, and build the auth UI yourself. The main reason to use Firebase Auth instead of Supabase is if you already have a Firebase backend (Firestore, Cloud Functions, Firebase Storage) or need specific Firebase Auth features like phone number authentication, anonymous auth, or integration with other Google Cloud services. The integration follows a standard pattern: initialize the Firebase app with your config, create an AuthProvider context that uses onAuthStateChanged to track the user session, and protect routes based on auth state. Firestore security rules can then reference the auth.uid to restrict data access.
- Firebase SDK not installed or not properly initialized with project configuration
- Firebase config values hardcoded in source code instead of stored in environment variables
- Auth state not persisted — user is logged out on every page refresh
- OAuth redirect URLs not configured in Firebase Console for your Lovable domain
- Firestore security rules not updated to use auth.uid for row-level security
Error messages you might see
Firebase: Error (auth/invalid-api-key)The Firebase API key is missing, incorrect, or not loaded from environment variables. Check that VITE_FIREBASE_API_KEY is set in Cloud tab > Secrets and matches your Firebase project.
Firebase: Error (auth/unauthorized-domain)Your Lovable app domain is not listed as an authorized domain in Firebase Console. Go to Firebase Console > Authentication > Settings > Authorized domains and add your lovable.app domain.
Firebase: Error (auth/popup-closed-by-user)The user closed the Google sign-in popup before completing authentication. This is not a code error. You can handle it by showing a message asking the user to try again.
Before you start
- A Firebase project created at console.firebase.google.com
- Firebase Authentication enabled in your Firebase project (Authentication > Sign-in method)
- Your Firebase web app config values (apiKey, authDomain, projectId, etc.)
- A Lovable project where you want to add Firebase Auth
How to fix it
Store Firebase config as environment variables in Lovable
Never hardcode API keys in source code — environment variables keep them secure and configurable per environment
Store Firebase config as environment variables in Lovable
Never hardcode API keys in source code — environment variables keep them secure and configurable per environment
Go to your Firebase Console > Project settings > General > Your apps > Web app. Copy the firebaseConfig values. In Lovable, click the + button next to Preview, open the Cloud tab, go to Secrets, and add each value: VITE_FIREBASE_API_KEY, VITE_FIREBASE_AUTH_DOMAIN, VITE_FIREBASE_PROJECT_ID, VITE_FIREBASE_STORAGE_BUCKET, VITE_FIREBASE_MESSAGING_SENDER_ID, VITE_FIREBASE_APP_ID. The VITE_ prefix ensures they are available in your frontend code at build time.
// Bad: hardcoded config in source codeconst firebaseConfig = { apiKey: "AIzaSyA...", authDomain: "myapp.firebaseapp.com",};// Good: config from environment variablesconst firebaseConfig = { apiKey: import.meta.env.VITE_FIREBASE_API_KEY, authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN, projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID, storageBucket: import.meta.env.VITE_FIREBASE_STORAGE_BUCKET, messagingSenderId: import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID, appId: import.meta.env.VITE_FIREBASE_APP_ID,};Expected result: Firebase config is loaded from environment variables. The values are not visible in source code.
Initialize Firebase and create an auth instance
The Firebase app must be initialized once before any auth operations can be performed
Initialize Firebase and create an auth instance
The Firebase app must be initialized once before any auth operations can be performed
Ask Lovable to install the firebase npm package and create a config file. The Firebase app should be initialized once in a dedicated file (src/lib/firebase.ts) and the auth instance exported for use throughout the app.
// No Firebase configuration exists// src/lib/firebase.tsimport { initializeApp } from "firebase/app";import { getAuth } from "firebase/auth";const firebaseConfig = { apiKey: import.meta.env.VITE_FIREBASE_API_KEY, authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN, projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID, storageBucket: import.meta.env.VITE_FIREBASE_STORAGE_BUCKET, messagingSenderId: import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID, appId: import.meta.env.VITE_FIREBASE_APP_ID,};const app = initializeApp(firebaseConfig);export const auth = getAuth(app);export default app;Expected result: Firebase is initialized and the auth instance is available for import throughout the app.
Create an AuthProvider with onAuthStateChanged
onAuthStateChanged listens for auth state changes and persists sessions across page refreshes automatically
Create an AuthProvider with onAuthStateChanged
onAuthStateChanged listens for auth state changes and persists sessions across page refreshes automatically
Create a context provider that wraps your app and tracks the current user. Use Firebase's onAuthStateChanged to listen for login/logout events and page refreshes. This ensures the user stays authenticated after a page reload without re-entering credentials. The provider should expose the user object, loading state, and sign-in/sign-out functions.
// No auth state management — user logged out on every refresh// src/components/AuthProvider.tsximport { createContext, useContext, useEffect, useState } from "react";import { User, onAuthStateChanged, signOut } from "firebase/auth";import { auth } from "@/lib/firebase";type AuthContextType = { user: User | null; loading: boolean; logout: () => Promise<void>;};const AuthContext = createContext<AuthContextType>({ user: null, loading: true, logout: async () => {}});export const useAuth = () => useContext(AuthContext);export const AuthProvider = ({ children }: { children: React.ReactNode }) => { const [user, setUser] = useState<User | null>(null); const [loading, setLoading] = useState(true); useEffect(() => { const unsubscribe = onAuthStateChanged(auth, (user) => { setUser(user); setLoading(false); }); return () => unsubscribe(); }, []); const logout = () => signOut(auth); return ( <AuthContext.Provider value={{ user, loading, logout }}> {children} </AuthContext.Provider> );};Expected result: Any component can use useAuth() to access the current user. Sessions persist across page refreshes.
Add sign-in methods and authorize your domain
Firebase Auth requires specific sign-in methods to be enabled and your app domain to be authorized
Add sign-in methods and authorize your domain
Firebase Auth requires specific sign-in methods to be enabled and your app domain to be authorized
In Firebase Console > Authentication > Sign-in method, enable the methods you need (Email/password, Google, etc.). Then go to Authentication > Settings > Authorized domains and add your Lovable domain (yourdomain.lovable.app). For Google sign-in, create the sign-in function using signInWithPopup. If configuring multiple auth providers and Firestore rules gets complex, RapidDev's engineers have integrated Firebase Auth across 600+ Lovable projects.
// No sign-in function existsimport { GoogleAuthProvider, signInWithPopup, signInWithEmailAndPassword } from "firebase/auth";import { auth } from "@/lib/firebase";// Google Sign-Inconst handleGoogleSignIn = async () => { const provider = new GoogleAuthProvider(); try { await signInWithPopup(auth, provider); } catch (error) { console.error("Google sign-in failed:", error); }};// Email/Password Sign-Inconst handleEmailSignIn = async (email: string, password: string) => { try { await signInWithEmailAndPassword(auth, email, password); } catch (error) { console.error("Email sign-in failed:", error); }};Expected result: Users can sign in with Google popup or email/password. The AuthProvider detects the sign-in and updates the user state.
Complete code example
1import { initializeApp } from "firebase/app";2import { getAuth } from "firebase/auth";3import { getFirestore } from "firebase/firestore";45// Firebase config loaded from environment variables6// Set these in Lovable Cloud tab > Secrets7const firebaseConfig = {8 apiKey: import.meta.env.VITE_FIREBASE_API_KEY,9 authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN,10 projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,11 storageBucket: import.meta.env.VITE_FIREBASE_STORAGE_BUCKET,12 messagingSenderId: import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID,13 appId: import.meta.env.VITE_FIREBASE_APP_ID,14};1516// Initialize Firebase app (only once)17const app = initializeApp(firebaseConfig);1819// Export auth instance for authentication20export const auth = getAuth(app);2122// Export Firestore instance for database operations23export const db = getFirestore(app);2425export default app;Best practices to prevent this
- Store all Firebase config values as VITE_ environment variables in Cloud tab > Secrets — never hardcode them
- Initialize Firebase once in a dedicated file (src/lib/firebase.ts) and export the instances
- Use onAuthStateChanged in an AuthProvider context to persist sessions across page refreshes
- Add your Lovable domain to Firebase Console > Authentication > Settings > Authorized domains
- Use signInWithPopup for OAuth providers (Google, GitHub) on desktop and signInWithRedirect on mobile
- Wrap your entire app with AuthProvider in App.tsx so all components can access useAuth()
- Set Firestore security rules to use request.auth.uid for row-level data access control
- Handle auth errors gracefully — show user-friendly messages instead of raw Firebase error codes
Still stuck?
Copy one of these prompts to get a personalized, step-by-step explanation.
I want to add Firebase Authentication to my Lovable project. I have a Firebase project set up. Please: 1. Show me the Firebase config file setup with environment variables 2. Create an AuthProvider context with onAuthStateChanged 3. Add Google sign-in and email/password sign-in functions 4. Create a login page component with both sign-in methods 5. Show me how to protect routes based on auth state 6. Write Firestore security rules that restrict data to authenticated users
Add Firebase Authentication to my project. Install the firebase npm package. Create @src/lib/firebase.ts with Firebase initialization using VITE_ environment variables. Create @src/components/AuthProvider.tsx with a React Context that uses onAuthStateChanged to track the current user. Add Google sign-in and email/password sign-in to @src/pages/Login.tsx. Wrap the app with AuthProvider in @src/App.tsx. Add a protected route wrapper that redirects to login if the user is not authenticated.
Frequently asked questions
Should I use Firebase Auth or Supabase Auth in Lovable?
Use Supabase Auth if you want the easiest setup — it is built into Lovable Cloud. Use Firebase Auth if you already have a Firebase backend, need phone authentication, or require Google Cloud integration. Both work well with Lovable.
Where do I store Firebase config values in Lovable?
In Cloud tab > Secrets. Add each value with a VITE_ prefix: VITE_FIREBASE_API_KEY, VITE_FIREBASE_AUTH_DOMAIN, etc. Access them in code with import.meta.env.VITE_FIREBASE_API_KEY.
How do I keep users logged in after page refresh?
Firebase Auth persists sessions in the browser automatically. Use onAuthStateChanged in your AuthProvider to listen for the session restoration on page load. Set loading to true initially and switch to false once onAuthStateChanged fires.
Why do I get an unauthorized-domain error?
Your Lovable app domain is not listed in Firebase's authorized domains. Go to Firebase Console > Authentication > Settings > Authorized domains and add your lovable.app domain and any custom domains.
Can I use Firebase Auth with Lovable's Supabase database?
Technically yes, but it requires custom integration. Supabase RLS expects Supabase Auth tokens. Using Firebase Auth with Supabase requires a custom JWT verification setup in Edge Functions. It is simpler to use one auth provider consistently.
What if I can't fix this myself?
If integrating Firebase Auth with your Lovable project involves complex OAuth flows, Firestore rules, or multi-provider setups, RapidDev's engineers can handle the full integration. They have set up Firebase Auth across 600+ projects.
Talk to an Expert
Our team has built 600+ apps. Get personalized help with your issue.
Book a free consultation