Coding exercise: implement JWT authentication in a React app.

React practical coding · Freshers and experienced

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

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