Developing a new e-commerce platform, blending StockX and eBay features, presented a steep learning curve. My first major project, I initially aimed for a completely custom-built solution, including authentication. This decision, however, highlighted the significant advantages of Firebase Auth over manual authentication.
Manual Authentication: The Initial Attempt
My initial approach involved a manual authentication system, alongside Firebase for data storage. The process was:
This initial implementation, shown below, seemed straightforward:
const submitFormData = async (path, data) => { // Store JWT token localStorage.setItem("token", responseData.data.token); console.log("Redirecting to home page"); location.replace("/"); }; subBtn.addEventListener("click", () => { // Form validation if (!tac.checked) { showAlert("you must agree to our terms and conditions"); } else { loader.style.display = "block"; submitFormData("/signup", { name: name.value, email: email.value, password: password.value, number: number.value, tac: tac.checked, notification: notification.checked, seller: false }); } });
The Roadblock
The problem arose when fetching user data from Firebase. The user object consistently returned null
. Hours of debugging revealed the limitations of my manual approach. Firebase Auth provided a far more elegant solution.
The Firebase Auth Solution: A Streamlined Approach
Switching to Firebase Auth dramatically simplified the process. The revised implementation:
const auth = getAuth(); createUserWithEmailAndPassword(auth, email.value, password.value) .then((userCredential) => { const user = userCredential.user; loader.style.display = "block"; return submitFormData("/signup", { name: name.value, email: email.value, password: password.value, number: number.value, tac: tac.checked, notification: notification.checked, seller: false }); }) .catch((error) => { showAlert(error.message); });
signInWithEmailAndPassword(auth, email.value, password.value) .then((userCredential) => { const user = userCredential.user; loader.style.display = "block"; return submitFormData("/login", { email: email.value, password: password.value }); }) .catch((error) => { showAlert(error.message); });
Key Improvements:
getAuth()
handles complex security configurations.createUserWithEmailAndPassword()
and signInWithEmailAndPassword()
manage email validation, password security, user creation, and session management automatically.Lessons Learned
Building authentication from scratch is a valuable learning experience, but Firebase Auth offers a secure, well-tested, and time-saving alternative. Its seamless integration with Firestore and built-in security features are invaluable for production applications. For production-ready software, leveraging established solutions like Firebase Auth is highly recommended.
The above is the detailed content of Firebase Auth vs Manual Auth: A Developers Journey. For more information, please follow other related articles on the PHP Chinese website!