Firebase Tutorial
- Home
- Introduction
- Project Setup
- Authentication (Email/Pass)
- Social Authentication
- Cloud Firestore (Basics)
- Firestore Queries
- Real-time Updates
- Firestore Security Rules
- Cloud Storage
- Storage Security Rules
- Cloud Functions (Intro)
- Triggering Functions
- Firebase Hosting
- Firebase Analytics
- Crashlytics & Performance
- Remote Config
- App Check
- Offline Persistence
- Firebase with Next.js
- Best Practices
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.