Coding exercise: implement JWT authentication in a React app.
Model answer
The server checks the password and returns a signed token. The client sends it in the Authorization header. The safest storage is an httpOnly cookie set by the server, because JavaScript (and so an XSS attack) cannot read it. Many apps keep the token in memory or localStorage for simplicity; know the trade-off.
// api.js: attach the token to every request
export async function api(path, options = {}) {
const token = localStorage.getItem('token');
const res = await fetch('/api' + path, {
...options,
headers: { 'Content-Type': 'application/json', ...(token && { Authorization: 'Bearer ' + token }), ...options.headers },
});
if (res.status === 401) { localStorage.removeItem('token'); window.location.assign('/login'); }
return res;
}
// Protect pages
function RequireAuth({ children }) {
return localStorage.getItem('token') ? children : <Navigate to="/login" replace />;
}On the server, hash passwords with bcrypt, sign the token with jwt.sign using a secret from the environment and a short expiry, and verify it in middleware. The React check only hides pages; the server must enforce access.
Tips
- Mention refresh tokens and logout, and that a hidden button is not security.
Practise it yourself in the React and Angular code playground.
Learn this topic
React.js Full Course: Beginner to Advanced .
Sign in to add your own answer.
More questions
- Coding exercise: build a Todo application in React.
- Coding exercise: create a search box with debounce in React.
- Coding exercise: fetch API data and display it in a table in React.
- Coding exercise: implement pagination in React.
- Coding exercise: create a login form with validation in React.
- Coding exercise: build a parent-child communication example in React.