Getting started with client side auth using React and Firebase Auth
1. Setting Up Your React Project
- Prerequisites: Node.js and npm or yarn installed.
- Instructions for creating a new React project using
create-react-app
or Vite.npm create vite@latest react-firebase-google-auth --template react
- Installing Firebase SDK:
npm install firebase
2. Configuring Firebase for Google Authentication
- Go to the Firebase Console and create a new project.
- Navigate to the “Authentication” section, click on “Get Started”, and then “Sign-in method”.
- Enable the Google sign-in provider and configure it:
- Enter the Project Support Email (possibly your email).
- Get the Firebase configuration keys from the project settings.
- Create a
firebase.js
file in your project to initialize Firebase:// src/firebase.js 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); export const auth = getAuth(app); export const googleProvider = new GoogleAuthProvider();
3. Setting Up Authentication Context in React
- Create a context to manage and provide authentication state throughout the app. The AuthContext plays a critical role in managing authentication state throughout your React application, providing a centralized way to access and update the user’s authentication status.
Why Use AuthContext for Authentication?
Centralized State Management: AuthContext keeps the user’s authentication state (like whether the user is logged in or not) centralized, which makes it easier to manage and maintain.
- Global Availability: All components in your app can access authentication-related data (e.g., current user, login status) without needing to pass down props through multiple levels.
- Reactivity: React components that consume the context will automatically re-render when the authentication state changes (e.g., a user logs in or logs out).
- Create an
AuthProvider
component that uses Firebase Auth to manage the user’s authentication state:// src/context/AuthContext.js import { createContext, useContext, useState, useEffect } from "react"; import { auth } from "../firebase"; import { onAuthStateChanged, signOut } from "firebase/auth"; const AuthContext = createContext(); export const useAuth = () => useContext(AuthContext); export const AuthProvider = ({ children }) => { const [currentUser, setCurrentUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { const unsubscribe = onAuthStateChanged(auth, (user) => { setCurrentUser(user); setLoading(false); }); return unsubscribe; }, []); const logout = () => signOut(auth); return ( <AuthContext.Provider value={{ currentUser, logout }}> {!loading && children} </AuthContext.Provider> ); };
4. Implementing Google Sign-In Functionality
- Create a
Login
component with a button for Google sign-in:// src/components/Login.js import { useAuth } from "../context/AuthContext"; import { auth, googleProvider } from "../firebase"; import { signInWithPopup } from "firebase/auth"; const Login = () => { const { currentUser } = useAuth(); const handleGoogleSignIn = async () => { try { await signInWithPopup(auth, googleProvider); } catch (error) { console.error("Error signing in with Google", error); } }; return ( <div> {currentUser ? ( <div> <p>Welcome, {currentUser.displayName}</p> </div> ) : ( <button onClick={handleGoogleSignIn}>Sign in with Google</button> )} </div> ); }; export default Login;
5. Protecting Routes Using React Router
-
Install React Router:
npm install react-router-dom
-
Create a
PrivateRoute
component to protect certain routes:// src/components/PrivateRoute.js import { useAuth } from "../context/AuthContext"; import { Navigate } from "react-router-dom"; const PrivateRoute = ({ children }) => { const { currentUser } = useAuth(); return currentUser ? children : <Navigate to="/login" />; }; export default PrivateRoute;
-
Use
PrivateRoute
to protect routes in your application:// src/App.js import { BrowserRouter as Router, Routes, Route } from "react-router-dom"; import { AuthProvider } from "./context/AuthContext"; import Login from "./components/Login"; import Dashboard from "./components/Dashboard"; import PrivateRoute from "./components/PrivateRoute"; function App() { return ( <AuthProvider> <Router> <Routes> <Route path="/login" element={<Login />} /> <Route path="/dashboard" element={<PrivateRoute><Dashboard /></PrivateRoute>} /> </Routes> </Router> </AuthProvider> ); } export default App;
6. Adding Logout Functionality
- Enhance the
Login
component to include a logout button for signed-in users:// src/components/Login.js import { useAuth } from "../context/AuthContext"; import { auth, googleProvider } from "../firebase"; import { signInWithPopup } from "firebase/auth"; const Login = () => { const { currentUser, logout } = useAuth(); const handleGoogleSignIn = async () => { try { await signInWithPopup(auth, googleProvider); } catch (error) { console.error("Error signing in with Google", error); } }; return ( <div> {currentUser ? ( <div> <p>Welcome, {currentUser.displayName}</p> <button onClick={logout}>Logout</button> </div> ) : ( <button onClick={handleGoogleSignIn}>Sign in with Google</button> )} </div> ); }; export default Login;
7. Styling the Components
- Suggestions for styling the authentication components using CSS or a popular styling framework like Tailwind CSS or Bootstrap.
8. Testing the Application
- Instructions for testing the Google sign-in functionality locally.
- Steps to deploy your app on a hosting platform (e.g., Firebase Hosting, Netlify, or Vercel).
Conclusion
- Recap of what was covered in the blog.
- Encourage readers to explore additional Firebase features or different authentication methods.
Code Repository
- Provide a link to the complete codebase on GitHub or any other code-sharing platform.
This revised outline will help you create a blog post focused specifically on implementing Google Authentication using Firebase in a React application.