Performance: JWT authentication flow
This affects page load speed and interaction responsiveness by how tokens are handled and verified during user authentication.
const [user, setUser] = useState(null);
useEffect(() => {
const token = localStorage.getItem('jwt');
if (token) {
// decode token asynchronously once on mount
decodeJWTAsync(token).then(setUser);
}
}, []);const token = localStorage.getItem('jwt'); if (token) { // decode and verify token on every render synchronously const user = decodeJWT(token); renderUser(user); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous JWT decode on every render | Minimal | 0 | High due to blocking JS | [X] Bad |
| Asynchronous JWT decode once on mount | Minimal | 0 | Low, non-blocking | [OK] Good |
| Reading token from localStorage on every request | Minimal | 0 | Low but repeated sync access | [!] OK |
| Caching token in memory for requests | Minimal | 0 | Lowest, no repeated sync access | [OK] Good |
import jwt from 'jsonwebtoken';
export async function get({ request }) {
const authHeader = request.headers.get('Authorization');
if (!authHeader) return new Response('No token', { status: 401 });
const token = authHeader.split(' ')[1];
try {
const user = jwt.verify(token, 'secretkey');
return new Response(`User: ${user.name}`, { status: 200 });
} catch {
return new Response('Invalid token', { status: 403 });
}
}export async function get({ request }) {
const authHeader = request.headers.get('Authorization');
if (!authHeader) return new Response('No token', { status: 401 });
const token = authHeader.split(' ')[0];
try {
const user = jwt.verify(token, 'secretkey');
return new Response(`User: ${user.name}`, { status: 200 });
} catch {
return new Response('Invalid token', { status: 403 });
}
}Pass the test and this pattern moves unknown