Home life · Updated
How to Implement Firebase Authentication
Quick answer You'll have email/password sign-up and login working in about 20 minutes by adding the Firebase SDK, creating a project, and calling two functions. This guide covers the web SDK (JavaScript) but the same steps apply to Android and iOS with their own SDKs.
Set Up a Firebase Project and Get Your Config
Go to the Firebase console, sign in with a Google account, and click Add project. Name it anything you like; you can leave Google Analytics off for now. Once the project is created, click the web icon (>) to register your app. Copy the firebaseConfig object that appears — it contains your API key, authDomain, projectId, and other values. You’ll paste this into your code in the next step.
In the Firebase console, go to Authentication in the left menu, then the Sign-in method tab. Enable the Email/Password provider. This is required for the sign-up and login functions to work.
Add the Firebase SDK to Your Project
If you’re using a plain HTML file, add these script tags before your own script:
<script src="https://www.gstatic.com/firebasejs/10.12.2/firebase-app-compat.js"></script> <script src="https://www.gstatic.com/firebasejs/10.12.2/firebase-auth-compat.js"></script>
If you’re using a module bundler like npm, install the packages with npm install firebase and import them in your JavaScript file. The version number may differ; check the Firebase docs for the current one.
Then initialize Firebase with the config you copied:
const firebaseConfig = {
apiKey: "...",
authDomain: "...",
projectId: "...",
// ... other values
};
firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();
Labels like apiKey and authDomain are standard and won’t change, but the exact values come from your project.
Create a Sign-Up Form and Handle Registration
Build a simple HTML form with email and password fields, plus a submit button. In your JavaScript, listen for the form’s submit event and call createUserWithEmailAndPassword:
document.getElementById('signup-form').addEventListener('submit', (e) => {
e.preventDefault();
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
auth.createUserWithEmailAndPassword(email, password)
.then((userCredential) => {
console.log('Signed up:', userCredential.user.email);
})
.catch((error) => {
console.error('Error:', error.message);
});
});
This creates a new user in Firebase Authentication. The password is stored securely by Firebase; you never handle it directly. After sign-up, the user is automatically signed in.
Add a Login Form and Handle Sign-In
Create a second form for login. Use signInWithEmailAndPassword:
document.getElementById('login-form').addEventListener('submit', (e) => {
e.preventDefault();
const email = document.getElementById('login-email').value;
const password = document.getElementById('login-password').value;
auth.signInWithEmailAndPassword(email, password)
.then((userCredential) => {
console.log('Signed in:', userCredential.user.email);
})
.catch((error) => {
console.error('Error:', error.message);
});
});
If the email or password is wrong, the catch block runs and you can show the error message to the user.
Listen for Auth State Changes and Protect Pages
Use onAuthStateChanged to detect whether a user is signed in. This runs once when the page loads and again whenever the auth state changes (sign-in, sign-out, token refresh).
auth.onAuthStateChanged((user) => {
if (user) {
// User is signed in; show protected content
document.getElementById('app').style.display = 'block';
} else {
// No user; show login/signup forms
document.getElementById('auth-forms').style.display = 'block';
}
});
For a real app, you also need to protect backend data. Firebase Security Rules control who can read and write to Firestore or Realtime Database. A common rule is to allow access only if request.auth != null. You set these in the Firebase console under Firestore Database or Realtime Database.
Add Sign-Out and Handle Errors
Add a sign-out button and call auth.signOut(). Then redirect the user to the login screen:
document.getElementById('signout-btn').addEventListener('click', () => {
auth.signOut()
.then(() => {
console.log('Signed out');
})
.catch((error) => {
console.error('Error:', error.message);
});
});
Common errors to handle in your catch blocks:
- auth/email-already-in-use — show “This email is already registered.”
- auth/invalid-email — show “Please enter a valid email address.”
- auth/weak-password — show “Password should be at least 6 characters.”
- auth/user-not-found — show “No account found with this email.”
- auth/wrong-password — show “Incorrect password.”
You can display these messages in a div on your page.
How to Tell It Worked
Open your app in a browser, fill in the sign-up form with a test email and password, and submit. If the console logs “Signed up: your@email.com”, the user was created. Then sign out and sign back in with the same credentials. You should see “Signed in: your@email.com”. In the Firebase console under Authentication > Users, you’ll see the new user listed with the email and a UID.
The One Failure People Hit and Its Fix
The most common problem is getting auth/operation-not-allowed when trying to sign up. This happens when the Email/Password sign-in method is not enabled in the Firebase console. Go to Authentication > Sign-in method, enable Email/Password, and save. Wait a few seconds and try again. Another frequent issue is a mismatch between the domain in your app and the authorized domains list. If you’re testing on a local server, add localhost to the authorized domains under Authentication > Settings.
Frequently Asked Questions
Do I need a paid plan to use Firebase Authentication?
No, the Spark plan includes email/password authentication for free. If you exceed the free tier’s usage limits, you’d need to upgrade, but for development and small apps it’s free.
Can I use Firebase Authentication with React or Vue?
Yes, the SDK works with any JavaScript framework. You’ll typically import the modular SDK (firebase/auth) and use the same functions. The setup steps are the same; only the import syntax differs.
How do I store extra user data like a name?
Use Firestore or Realtime Database. After sign-up, create a document in Firestore with the user’s UID as the document ID and store fields like name and email. You can also update the user’s profile with user.updateProfile({ displayName: "..." }).
Related
- How to Give Access to a Firebase Project
- Fix WiFi Authentication Error: Step-by-Step Guide
- T-Mobile Privacy Settings: What You Can Change
Sources: Firebase Documentation. Menus and buttons can differ slightly by version. Spotted something out of date? Tell us.