Skip to main content
RapidDev - Software Development Agency
lovable-issues

Integrating Firebase Authentication with Lovable Projects

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.

Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Intermediate7 min read~20 minAll Lovable projects (requires Firebase project)March 2026RapidDev Engineering Team
TL;DR

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

1

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.

Before
typescript
// Bad: hardcoded config in source code
const firebaseConfig = {
apiKey: "AIzaSyA...",
authDomain: "myapp.firebaseapp.com",
};
After
typescript
// Good: config from environment variables
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,
};

Expected result: Firebase config is loaded from environment variables. The values are not visible in source code.

2

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.

Before
typescript
// No Firebase configuration exists
After
typescript
// src/lib/firebase.ts
import { 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.

3

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.

Before
typescript
// No auth state management — user logged out on every refresh
After
typescript
// src/components/AuthProvider.tsx
import { 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.

4

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.

Before
typescript
// No sign-in function exists
After
typescript
import { GoogleAuthProvider, signInWithPopup, signInWithEmailAndPassword } from "firebase/auth";
import { auth } from "@/lib/firebase";
// Google Sign-In
const handleGoogleSignIn = async () => {
const provider = new GoogleAuthProvider();
try {
await signInWithPopup(auth, provider);
} catch (error) {
console.error("Google sign-in failed:", error);
}
};
// Email/Password Sign-In
const 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

src/lib/firebase.ts
1import { initializeApp } from "firebase/app";
2import { getAuth } from "firebase/auth";
3import { getFirestore } from "firebase/firestore";
4
5// Firebase config loaded from environment variables
6// Set these in Lovable Cloud tab > Secrets
7const 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};
15
16// Initialize Firebase app (only once)
17const app = initializeApp(firebaseConfig);
18
19// Export auth instance for authentication
20export const auth = getAuth(app);
21
22// Export Firestore instance for database operations
23export const db = getFirestore(app);
24
25export 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.

ChatGPT Prompt

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

Lovable Prompt

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.

RapidDev

Talk to an Expert

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

Book a free consultation

Need help with your Lovable project?

Our experts have built 600+ apps and can solve your issue fast. 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.