React + Backend Token Authentication Workflow
This guide explains how React works with a backend API using tokens for authentication, in very
simple terms. We’ll imagine we are building a small e-commerce site where users can log in, view
products, and buy items.
1. Landing on the Website
When you first visit the site, React checks if a token is stored (in localStorage). If not found, you are
treated as a guest and see Login/Signup buttons.
const token = localStorage.getItem("token");
if (!token) {
// Show Login/Signup
}
2. Login or Signup — Getting the Token
When you log in, React sends your email and password to the backend API. If correct, the backend
sends back a token (like a digital key).
const res = await fetch("/api/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password })
});
const data = await res.json();
localStorage.setItem("token", data.token);
3. Auto-Login on Page Load
React can automatically check for a token on page load. If found, it sends it to the backend to get
the logged-in user's data.
useEffect(() => {
const token = localStorage.getItem("token");
if (token) {
fetch("/api/me", { headers: { Authorization: "Bearer " + token } })
.then(res => res.json())
.then(data => setUser(data));
}
}, []);
4. Viewing Public Data (Products)
Some API data is public (like product lists) and doesn’t require a token.
const res = await fetch("/api/products");
const products = await res.json();
5. Doing Authenticated Actions (Buy, Cart, etc.)
For actions like buying a product, React sends the token so the backend knows who you are.
const token = localStorage.getItem("token");
await fetch("/api/buy/123", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + token
},
body: JSON.stringify({ quantity: 1 })
});
6. Logout
When the user clicks Logout, remove the token and clear the user state.
localStorage.removeItem("token");
setUser(null);
Summary
Think of the token as a membership card. You get it after logging in, keep it in your wallet
(localStorage), and show it to the backend whenever you need access to protected features.
Without it, you can only view public data.