Home life · Updated
How to Use Firebase for Authentication
Quick answer You can add email/password login to your web or mobile app with Firebase Authentication in about 30 minutes. You'll create a Firebase project, enable the sign-in method, then add the SDK and call a few functions.
Before You Start: What You Need
You need a Google account to sign in to the Firebase console, and an existing app (web, Android, or iOS) where you want to add login. For this guide, we’ll use the web SDK, but the console steps are the same for all platforms. Make sure your app is running locally or on a test server so you can test the redirect.
Step 1: Create a Firebase Project
- Go to the Firebase console at console.firebase.google.com and sign in with your Google account.
- Click “Add project”, enter a project name (like “MyApp”), and click “Continue”.
- Disable Google Analytics for now (you can enable it later) and click “Create project”. Wait for the project to be ready, then click “Continue”.
Step 2: Register Your App
- In the project overview, click the web icon (>) to add a web app. If you’re using Android or iOS, click the corresponding icon instead.
- Enter a nickname for your app (like “MyWebApp”) and click “Register app”.
- Copy the firebaseConfig object that appears. It looks like a block of JavaScript with keys like apiKey, authDomain, and projectId. Keep this safe; you’ll paste it into your code.
- Click “Continue to console” after copying the config.
Step 3: Enable Email/Password Sign-In
- In the Firebase console, go to “Build” > “Authentication” in the left sidebar.
- Click “Get started” if prompted, then click the “Sign-in method” tab.
- Click “Email/Password”, toggle “Enable” to on, and click “Save”.
Step 4: Add the Firebase SDK to Your App
- In your HTML file, add the Firebase SDK scripts before your own script tag. Use the modular SDK (v9+) for new projects; the exact script tags are shown in the console under “Project settings” > “Your apps”.
- Initialize Firebase with the config you copied earlier. In your JavaScript, add:
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
If you’re not using a bundler, use the CDN version and include the config directly in a script tag.
Step 5: Create a Sign-Up Form
- Add an HTML form with email and password fields, and a submit button. For example:
<form id="signup-form"> <input type="email" id="email" placeholder="Email" required> <input type="password" id="password" placeholder="Password" required> <button type="submit">Sign Up</button> </form>
- Add a submit event listener that calls
createUserWithEmailAndPassword:
import { createUserWithEmailAndPassword } from "firebase/auth";
document.getElementById("signup-form").addEventListener("submit", (e) => {
e.preventDefault();
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
console.log("Signed up:", userCredential.user);
})
.catch((error) => {
console.error("Error:", error.message);
});
});
Step 6: Add a Sign-In Form
- Create a second form (or a toggle) for existing users, with the same email and password fields.
- Add a submit handler that calls
signInWithEmailAndPassword:
import { signInWithEmailAndPassword } from "firebase/auth";
document.getElementById("login-form").addEventListener("submit", (e) => {
e.preventDefault();
const email = document.getElementById("login-email").value;
const password = document.getElementById("login-password").value;
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
console.log("Signed in:", userCredential.user);
})
.catch((error) => {
console.error("Error:", error.message);
});
});
Step 7: Observe the User State
- Use
onAuthStateChangedto detect when a user signs in or out, and update your UI accordingly:
import { onAuthStateChanged } from "firebase/auth";
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in
document.getElementById("user-info").textContent = "Logged in as: " + user.email;
} else {
// User is signed out
document.getElementById("user-info").textContent = "Not logged in";
}
});
What to Check First When It Doesn’t Work
If login fails, check the browser console for error messages. The most common causes are:
| Symptom | Cause | Fix |
|---|---|---|
| “auth/operation-not-allowed” | Email/password sign-in is not enabled in the Firebase console. | Go to Authentication > Sign-in method and enable Email/Password. |
| “auth/invalid-api-key” | The API key in your config is wrong or missing. | Copy the config again from Project settings > Your apps, and paste it exactly. |
| “auth/email-already-in-use” | The email is already registered. | Use a different email or check if the user is already signed in. |
| “auth/wrong-password” | The password doesn’t match the email. | Use the password reset flow (sendPasswordResetEmail) to let the user reset it. |
How to Sign Out and Protect Routes
To sign out, call signOut(auth). To protect pages, check the user state before rendering sensitive content. For a simple web app, you can redirect unauthenticated users to a login page:
import { signOut } from "firebase/auth";
signOut(auth).then(() => {
window.location.href = "/login";
});
Common Mistakes and What They Cause
- Wrong config values: Copying the config from an old project causes “auth/api-key-not-valid” errors. Always use the config from your current project.
- Forgetting to enable the sign-in method: If you skip step 3, every sign-up attempt fails with “operation-not-allowed”.
- Using the wrong SDK version: Mixing v8 and v9 syntax causes “getAuth is not a function”. Stick to one version and import consistently.
- Not handling errors: Without a .catch block, errors are silent and the user sees nothing. Always show the error message to the user.
How to Add Password Reset and Email Verification
To let users reset their password, call sendPasswordResetEmail(auth, email). For email verification, use sendEmailVerification(user) after sign-up. Both functions return a promise you can await; show a confirmation message when they resolve.
Frequently Asked Questions
Can I use Firebase Authentication with React or Vue?
Yes. The SDK works with any JavaScript framework. Install the firebase package via npm and import the functions as shown. The main difference is where you put the event listeners—use useEffect in React or mounted in Vue.
How do I store extra user data like a display name?
Update the user’s profile with updateProfile(user, { displayName: "Jane" }). For more complex data, use Firebase Firestore and store a document with the user’s UID as the document ID.
Is Firebase Authentication free?
Firebase Authentication has a free tier that includes 50,000 monthly active users for email/password sign-in. Beyond that, you pay per active user, but for most small apps the free tier is enough.
Related
- How to Implement Firebase Authentication
- Fix WiFi Authentication Error: Step-by-Step Guide
- Create a Firebase Account: Step-by-Step
Sources: Firebase Documentation. Menus and buttons can differ slightly by version. Spotted something out of date? Tell us.