Table of Contents
Implementing secure authentication in a React application is essential for protecting user data and providing a seamless login experience. Firebase Authentication offers a robust and easy-to-integrate solution, while React Context allows for efficient state management across your app. This tutorial guides you through setting up user authentication using Firebase and React Context.
Prerequisites
- Basic knowledge of React and JavaScript
- Node.js and npm installed
- Firebase project setup
- React application created with Create React App or similar
Step 1: Set Up Firebase
Go to the Firebase Console and create a new project. Enable Email/Password authentication in the Authentication section. Then, add your web app to Firebase and copy the Firebase configuration object.
Install Firebase SDK in your React project:
npm install firebase
Create a file named firebase.js in your src directory and initialize Firebase:
import { initializeApp } from 'firebase/app';
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 default app;
Step 2: Create Authentication Context
Set up a React Context to manage authentication state globally. Create a new file AuthContext.js.
import React, { createContext, useState, useEffect } from 'react';
import { getAuth, onAuthStateChanged, signInWithEmailAndPassword, signOut } from 'firebase/auth';
import app from './firebase';
export const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const auth = getAuth(app);
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
setUser(user);
setLoading(false);
});
return () => unsubscribe();
}, [auth]);
const login = (email, password) => {
return signInWithEmailAndPassword(auth, email, password);
};
const logout = () => {
return signOut(auth);
};
return (
{children}
);
};
Step 3: Create Login and Logout Components
Build components for user login and logout functionalities.
import React, { useState, useContext } from 'react';
import { AuthContext } from './AuthContext';
const Login = () => {
const { login } = useContext(AuthContext);
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
await login(email, password);
} catch (err) {
setError(err.message);
}
};
return (
);
};
export default Login;
import React, { useContext } from 'react';
import { AuthContext } from './AuthContext';
const Logout = () => {
const { logout } = useContext(AuthContext);
const handleLogout = () => {
logout();
};
return ;
};
export default Logout;
Step 4: Protect Routes and Display User Info
Create a component to display user info and protect routes based on authentication status.
import React, { useContext } from 'react';
import { AuthContext } from './AuthContext';
const Dashboard = () => {
const { user, loading } = useContext(AuthContext);
if (loading) {
return Loading...
;
}
if (!user) {
return Please log in to access the dashboard.
;
}
return (
Welcome, {user.email}
);
};
export default Dashboard;
Step 5: Integrate Everything in App.js
Wrap your application with AuthProvider and include the login, logout, and dashboard components.
import React from 'react';
import { AuthProvider } from './AuthContext';
import Login from './Login';
import Logout from './Logout';
import Dashboard from './Dashboard';
function App() {
return (
);
}
export default App;
Conclusion
By following these steps, you can implement a secure login system in your React application using Firebase Authentication and React Context. This setup provides a foundation for adding more features like registration, password reset, and user profile management.