Introduction

Authentication is one of the most important parts of any modern web application. Whether you are building a React app, a SaaS platform, or an enterprise system, securing user data is critical.

One of the most popular and widely used methods for authentication is JWT (JSON Web Token). It allows secure communication between the client (React app) and the server (backend API).

In this article, we will learn how to implement authentication in React using JWT step by step in simple words, with practical examples and best practices.

What is JWT (JSON Web Token)?

JWT is a secure token that is used to verify the identity of a user.

It contains encoded information such as:

Example of JWT Structure

A JWT has three parts:

Header.Payload.Signature

Example:
abc123.xyz456.signature789

Why Use JWT?

How JWT Authentication Works

Flow

  1. User logs in using email and password

  2. Server validates credentials

  3. Server generates JWT token

  4. Token is sent to React app

  5. React stores token (localStorage or cookies)

  6. Token is sent with every API request

  7. Server verifies token and responds

Project Setup (React + Backend)

Step 1: Create React App

Bash
npx create-react-app jwt-auth-app
cd jwt-auth-app
npm install axios react-router-dom

Step 2: Backend Setup (Node.js Example)

Bash
npm init -y
npm install express jsonwebtoken cors bcryptjs

Backend Implementation (JWT API)

Create Server

JavaScript
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();

app.use(express.json());

const SECRET_KEY = "your_secret_key";

app.post('/login', (req, res) => {
  const { email, password } = req.body;

  if (email === "[email protected]" && password === "123456") {
    const token = jwt.sign({ email }, SECRET_KEY, { expiresIn: '1h' });
    return res.json({ token });
  }

  res.status(401).json({ message: "Invalid credentials" });
});

app.listen(5000, () => console.log("Server running"));

React Implementation (Frontend)

Step 3: Create Login Component

JavaScript
import React, { useState } from "react";
import axios from "axios";

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

  const handleLogin = async () => {
    try {
      const res = await axios.post("http://localhost:5000/login", {
        email,
        password
      });

      localStorage.setItem("token", res.data.token);
      alert("Login Successful");
    } catch (err) {
      alert("Login Failed");
    }
  };

  return (
    <div>
      <input placeholder="Email" onChange={(e) => setEmail(e.target.value)} />
      <input placeholder="Password" type="password" onChange={(e) => setPassword(e.target.value)} />
      <button onClick={handleLogin}>Login</button>
    </div>
  );
}

export default Login;

Step 4: Store and Use JWT Token

After login, store the token:

JavaScript
localStorage.setItem("token", token);

Send token with API requests:

JavaScript
const token = localStorage.getItem("token");

axios.get("http://localhost:5000/protected", {
  headers: {
    Authorization: `Bearer ${token}`
  }
});

Step 5: Protect Routes in React

Create a Private Route:

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

const PrivateRoute = ({ children }) => {
  const token = localStorage.getItem("token");
  return token ? children : <Navigate to="/login" />;
};

export default PrivateRoute;

Step 6: Backend Token Verification

JavaScript
const verifyToken = (req, res, next) => {
  const token = req.headers['authorization']?.split(' ')[1];

  if (!token) return res.status(403).send("Token required");

  jwt.verify(token, SECRET_KEY, (err, decoded) => {
    if (err) return res.status(401).send("Invalid token");

    req.user = decoded;
    next();
  });
};

Step 7: Create Protected API

JavaScript
app.get('/protected', verifyToken, (req, res) => {
  res.json({ message: "Protected data", user: req.user });
});

Best Practices for JWT Authentication

Common Mistakes to Avoid

Real-World Use Cases

Key Takeaways

Summary

JWT authentication in React is a powerful and scalable way to secure modern web applications. By generating a token on login, storing it securely, and sending it with every API request, developers can build secure authentication systems. With proper implementation, including route protection and token validation, JWT helps create reliable, fast, and secure user experiences in React applications.