Authentication is a crucial aspect of web applications, allowing you to manage user access and secure sensitive information. In the React ecosystem, there are various ways to implement authentication, from using local storage for tokens to leveraging backend services. In this blog post, we'll walk through the fundamental steps of handling authentication in React while building a simple example application.
Before diving in, let's clarify a few key concepts:
For this example, we will build a simple login form that authenticates users via JSON Web Tokens (JWT). We will also protect specific routes based on the authentication state.
First, we'll set up a basic React app using Create React App:
npx create-react-app react-auth-example cd react-auth-example npm start
Next, we need a simple backend API for authentication. If you have a Node.js backend, you can utilize libraries like express
and jsonwebtoken
. For now, let's focus on the frontend.
Your project structure should look like this:
react-auth-example/
├── src/
│ ├── components/
│ │ ├── Login.jsx
│ │ ├── ProtectedRoute.jsx
│ │ └── Home.jsx
│ ├── App.jsx
│ └── index.js
The login component will handle user input for authentication. Here's how you can create a simple login form:
// src/components/Login.jsx import React, { useState } from 'react'; const Login = ({ onLogin }) => { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const handleSubmit = async (e) => { e.preventDefault(); // Simulating an API call const response = await fakeApiCall(username, password); if (response.token) { onLogin(response.token); } else { alert('Login failed'); } }; const fakeApiCall = (username, password) => { // Note: This is a placeholder for a real API call. return new Promise((resolve) => { setTimeout(() => { if (username === "admin" && password === "admin") { resolve({ token: "fake-jwt-token" }); } else { resolve({}); } }, 1000); }); }; return ( <form onSubmit={handleSubmit}> <div> <label>Username:</label> <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} required /> </div> <div> <label>Password:</label> <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required /> </div> <button type="submit">Login</button> </form> ); }; export default Login;
In your main App component, you will manage the authentication state using React's useState
hook. We will store the token in local storage for this example.
// src/App.jsx import React, { useState } from 'react'; import { BrowserRouter as Router, Route, Routes, Navigate } from 'react-router-dom'; import Login from './components/Login'; import Home from './components/Home'; const App = () => { const [token, setToken] = useState(localStorage.getItem('token')); const handleLogin = (token) => { setToken(token); localStorage.setItem('token', token); }; const handleLogout = () => { setToken(null); localStorage.removeItem('token'); }; return ( <Router> <Routes> <Route path="/login" element={!token ? <Login onLogin={handleLogin} /> : <Navigate to="/" />} /> <Route path="/" element={<Home token={token} onLogout={handleLogout} />} /> </Routes> </Router> ); }; export default App;
The Home component will display a welcome message and a logout button for the authenticated user.
// src/components/Home.jsx import React from 'react'; const Home = ({ token, onLogout }) => { return ( <div> <h1>Welcome!</h1> {token && <button onClick={onLogout}>Logout</button>} </div> ); }; export default Home;
To protect routes that require authentication, we can create a ProtectedRoute
component:
// src/components/ProtectedRoute.jsx import React from 'react'; import { Navigate } from 'react-router-dom'; const ProtectedRoute = ({ element, token }) => { return token ? element : <Navigate to="/login" />; }; export default ProtectedRoute;
You can then use this component in your routing setup to protect the Home route:
import ProtectedRoute from './components/ProtectedRoute'; // In your App component <Route path="/" element={<ProtectedRoute element={<Home token={token} onLogout={handleLogout} />} token={token} />} />
That’s it! You now have a simple authentication system in place for your React application. Remember, this example uses a simulated API call for demonstration purposes. In a real-world application, you would replace the fake API with actual calls to your backend service.
Feel free to expand on this base implementation by adding features like password recovery, email verification, or multi-factor authentication for a more robust authentication system.
24/08/2024 | ReactJS
14/09/2024 | ReactJS
21/07/2024 | ReactJS
28/11/2024 | ReactJS
14/09/2024 | ReactJS
14/09/2024 | ReactJS
24/08/2024 | ReactJS
24/08/2024 | ReactJS
24/08/2024 | ReactJS