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:
User ID
Email
Expiration time
Example of JWT Structure
A JWT has three parts:
Header.Payload.Signature
Example:
abc123.xyz456.signature789
Why Use JWT?
How JWT Authentication Works
Flow
User logs in using email and password
Server validates credentials
Server generates JWT token
Token is sent to React app
React stores token (localStorage or cookies)
Token is sent with every API request
Server verifies token and responds
Project Setup (React + Backend)
Step 1: Create React App
npx create-react-app jwt-auth-app
cd jwt-auth-app
npm install axios react-router-dom
Step 2: Backend Setup (Node.js Example)
npm init -y
npm install express jsonwebtoken cors bcryptjs
Backend Implementation (JWT API)
Create Server
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
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:
localStorage.setItem("token", token);
Send token with API requests:
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:
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
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
app.get('/protected', verifyToken, (req, res) => {
res.json({ message: "Protected data", user: req.user });
});
Best Practices for JWT Authentication
Use HTTPS for secure communication
Store tokens securely (avoid XSS attacks)
Use short expiration time
Implement refresh tokens
Validate tokens on every request
Common Mistakes to Avoid
Storing sensitive data in JWT
Not handling token expiration
Using weak secret keys
Ignoring security vulnerabilities
Real-World Use Cases
Key Takeaways
JWT is a popular authentication method
React handles frontend authentication
Backend generates and verifies tokens
Secure storage and validation are critical
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.