Introduction
Authentication is one of the most important features that needs to be implemented in most of the apps. Firebase Authentication makes it easy to manage user authentication in your React applications. In this blog, we will set up Firebase authentication in a React app, using Email/Password Authentication and Google Sign-In. Once you understand those 2 you can also try with other sign-in methods as they are mostly the same. To demonstrate, we will integrate this authentication setup into a simple Todo App.
Step 1: Setting Up a React Project with Vite
First, create a new React project using Vite:
npm create vite@latest todo-app --template react
cd todo-app
npm install
Next, install Firebase:
npm install firebase
Step 2: Setting Up Firebase
- Go to Firebase Console.
- Click Create a Project and follow the setup steps.
- In the Authentication section, enable:
- Email/Password Authentication
- Google Sign-In
- In Project Settings, under the General tab, find your Firebase SDK configuration. Copy the
firebaseConfig
object.
Step 3: Configuring Firebase in React
Create a new file src/firebase.js
and add the following:
import { initializeApp } from "firebase/app";
import { getAuth, GoogleAuthProvider } from "firebase/auth";
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const googleProvider = new GoogleAuthProvider();
export { auth, googleProvider };
Step 4: Creating Authentication Components
1. Sign Up Component
Create a src/components/SignUp.js
file:
import { useState } from "react";
import { auth } from "../firebase";
import { createUserWithEmailAndPassword } from "firebase/auth";
const SignUp = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const handleSignUp = async () => {
try {
await createUserWithEmailAndPassword(auth, email, password);
alert("User registered Successfully!");
} catch (error) {
alert(error.message);
}
};
return (
<div>
<h2>Sign Up</h2>
<label>Email</label>
<input
type="email"
placeholder="Enter the Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<label>Password</label>
<input
type="password"
placeholder="Enter the Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button onClick={handleSignUp}>Sign Up</button>
</div>
);
};
export default SignUp;
2. Login Component
Create a src/components/Login.js
file:
import { useState } from "react";
import { auth, googleProvider } from "../firebase";
import { signInWithEmailAndPassword, signInWithPopup } from "firebase/auth";
const Login = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const handleLogin = async () => {
try {
await signInWithEmailAndPassword(auth, email, password);
alert("Login Successful!");
} catch (error) {
alert(error.message);
}
};
const handleGoogleLogin = async () => {
try {
await signInWithPopup(auth, googleProvider);
alert("Google Login Successful!");
} catch (error) {
alert(error.message);
}
};
return (
<div>
<h2>Login</h2>
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button onClick={handleLogin}>Login</button>
<button onClick={handleGoogleLogin}>Login with Google</button>
</div>
);
};
export default Login;
Step 5: Protecting the Todo App
Now, integrate authentication into the Todo App. Create a src/App.js
file:
import { useState, useEffect } from "react";
import { auth } from "./firebase";
import { onAuthStateChanged, signOut } from "firebase/auth";
import SignUp from "./components/SignUp";
import Login from "./components/Login";
const App = () => {
const [user, setUser] = useState(null);
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
setUser(currentUser);
});
return () => unsubscribe();
}, []);
return (
<div>
{user ? (
<div>
<h2>Welcome, {user.email}</h2>
<button onClick={() => signOut(auth)}>Logout</button>
<TodoApp />
</div>
) : (
<div>
<SignUp />
<Login />
</div>
)}
</div>
);
};
export default App;
Step 6: Creating the Todo App
Create src/components/TodoApp.js
:
import { useState } from "react";
const TodoApp = () => {
const [todos, setTodos] = useState([]);
const [input, setInput] = useState("");
const addTodo = () => {
if (input.trim()) {
setTodos([...todos, input]);
setInput("");
}
};
return (
<div>
<h2>Todo List</h2>
<input
type="text"
placeholder="Add a task"
value={input}
onChange={(e) => setInput(e.target.value)}
/>
<button onClick={addTodo}>Add</button>
<ul>
{todos.map((todo, index) => (
<li key={index}>{todo}</li>
))}
</ul>
</div>
);
};
export default TodoApp;
Conclusion
Now, as you have successfully integrated Firebase Authentication into a React App with Email/Password Authentication and Google Sign-In. You can now protect your app's features based on user authentication! You can take the project a step further and implement role-based authentication, and public and protected routes based on user authentication. If you like this blog and want to learn more about Frontend Development and Software Engineering, you can follow me on Dev.to.
Top comments (0)