Authentication in React

🔐 React Authentication from Scratch: A Beginner-Friendly Guide

Date: June 17, 2025
Author: Champak Roy


🧭 Introduction

When you build web apps, especially ones with private user areas (like dashboards or profiles), authentication becomes essential. Authentication ensures that only the right users can access certain parts of your app.

In this post, we’ll break down how authentication works in React, step-by-step. We'll keep it beginner-friendly and cover everything from login forms to token handling and route protection.


📚 Keywords

  • React
  • Authentication
  • JWT
  • Login
  • Protected Routes
  • React Router
  • useState
  • useEffect

🧠 Why is Authentication Important?

Authentication is like a security guard for your app. Without it:

  • Anyone can access any page (even admin pages).
  • Users can’t save or view their personalized content.
  • There's no way to identify who is using your app.

🏗️ What We'll Build

We’ll create a simple login system with:

  1. A login page
  2. A fake authentication API
  3. Route protection (hiding certain pages unless logged in)
  4. Logout functionality

⚙️ Tools Needed

  • React (using create-react-app)
  • React Router
  • JSON Web Token (JWT) for simulating real-world behavior

1️⃣ Setting Up the Project

npx create-react-app react-auth-demo
cd react-auth-demo
npm install react-router-dom

2️⃣ Setting Up Routing

// App.js
import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Home from "./Home";
import Login from "./Login";
import Dashboard from "./Dashboard";
import ProtectedRoute from "./ProtectedRoute";

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/login" element={<Login />} />
        <Route
          path="/dashboard"
          element={
            <ProtectedRoute>
              <Dashboard />
            </ProtectedRoute>
          }
        />
      </Routes>
    </Router>
  );
}

export default App;

3️⃣ Creating Pages

Home.js


import React from "react";
import { Link } from "react-router-dom";

export default function Home() {
  return (
    <div>
      <h1>Welcome Home</h1>
      <Link to="/login">Login</Link> | <Link to="/dashboard">Dashboard</Link>
    </div>
  );
}

Dashboard.js


import React from "react";

export default function Dashboard() {
  return <h1>Welcome to your Dashboard!</h1>;
}

4️⃣ Creating the Login Page

Login.js


import React, { useState } from "react";
import { useNavigate } from "react-router-dom";

export default function Login() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const navigate = useNavigate();

  const fakeAuth = (email, password) => {
    return email === "user@example.com" && password === "123456";
  };

  const handleLogin = (e) => {
    e.preventDefault();
    if (fakeAuth(email, password)) {
      localStorage.setItem("token", "mock-jwt-token");
      navigate("/dashboard");
    } else {
      alert("Invalid credentials");
    }
  };

  return (
    <form onSubmit={handleLogin}>
      <h2>Login</h2>
      <input
        type="email"
        placeholder="Email"
        onChange={(e) => setEmail(e.target.value)}
        required
      /><br />
      <input
        type="password"
        placeholder="Password"
        onChange={(e) => setPassword(e.target.value)}
        required
      /><br />
      <button type="submit">Login</button>
    </form>
  );
}

5️⃣ Protecting Routes

ProtectedRoute.js


import React from "react";
import { Navigate } from "react-router-dom";

export default function ProtectedRoute({ children }) {
  const isAuthenticated = localStorage.getItem("token");
  return isAuthenticated ? children : <Navigate to="/login" />;
}

6️⃣ Logging Out


const logout = () => {
  localStorage.removeItem("token");
  window.location.href = "/";
};

You can place this logout function in a button on the dashboard or navbar.


🧪 Testing the Flow

  1. Visit /dashboard → Redirects to /login (not logged in).
  2. Login with:
    • Email: user@example.com
    • Password: 123456
  3. You’re redirected to the Dashboard.
  4. Refreshing the page keeps you on the dashboard because of the token.
  5. Remove token to log out.

🔐 Real-World Notes

  • Never store JWT in localStorage (consider HttpOnly cookies instead).
  • Validate tokens on the server.
  • Use real APIs for login and user data.
  • Use axios or fetch to communicate with the backend.

🧠 Summary

We’ve covered:

  • ✅ Login form
  • ✅ Simulated authentication
  • ✅ Route protection
  • ✅ Token storage
  • ✅ Logout

This is a solid foundation for React authentication. From here, you can expand into registration, role-based access, user profiles, and more.


🧩 Sample Repository

👉 GitHub Example (Coming Soon)


📞 Get In Touch

Need help with your React project?
💬 Contact on WhatsApp

Post a Comment

0 Comments

Me