Authentication (Email/Pass)
Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports various methods, but Email and Password is the most common.
1. Enable Email/Password
- Go to Authentication in the Firebase Console.
- Click "Sign-in method" tab.
- Enable Email/Password and click Save.
2. Sign Up a User
Use the createUserWithEmailAndPassword function to register new users.
import { auth } from "../lib/firebase";
import { createUserWithEmailAndPassword } from "firebase/auth";
const signUp = async (email, password) => {
try {
const userCredential = await createUserWithEmailAndPassword(auth, email, password);
const user = userCredential.user;
console.log("Registered user:", user);
} catch (error) {
console.error("Sign-up Error:", error.message);
}
};
3. Sign In a User
Use signInWithEmailAndPassword to log in existing users.
import { auth } from "../lib/firebase";
import { signInWithEmailAndPassword } from "firebase/auth";
const login = async (email, password) => {
try {
const userCredential = await signInWithEmailAndPassword(auth, email, password);
alert("Welcome back!");
} catch (error) {
console.error("Login Error:", error.message);
}
};
4. Sign Out
import { auth } from "../lib/firebase";
import { signOut } from "firebase/auth";
auth.signOut().then(() => {
console.log("User signed out");
});
Check Current Auth State: Use onAuthStateChanged to listen for authentication state changes and update your UI.