0
0
Expressframework~8 mins

JWT token verification middleware in Express - Performance & Optimization

Choose your learning style9 modes available
Performance: JWT token verification middleware
MEDIUM IMPACT
This affects the server response time and user interaction speed by adding token verification before processing requests.
Verifying JWT tokens on incoming API requests
Express
import { promisify } from 'util';
const verifyAsync = promisify(jwt.verify);
app.use(async (req, res, next) => {
  try {
    const token = req.headers.authorization?.split(' ')[1];
    if (!token) return res.status(401).send('No token');
    req.user = await verifyAsync(token, 'secret');
    next();
  } catch {
    res.status(403).send('Invalid token');
  }
});
Using async verification avoids blocking the event loop, improving server responsiveness and user interaction speed.
📈 Performance GainNon-blocking verification reduces request latency and improves INP metric.
Verifying JWT tokens on incoming API requests
Express
app.use((req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).send('No token');
  jwt.verify(token, 'secret', (err, decoded) => {
    if (err) return res.status(403).send('Invalid token');
    req.user = decoded;
    next();
  });
});
Synchronous or blocking verification with no caching causes delay on every request, increasing server response time.
📉 Performance CostBlocks request processing for each token verification, increasing INP and server CPU usage.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Synchronous JWT verification middleware0 (server-side)00[X] Bad
Asynchronous JWT verification middleware0 (server-side)00[OK] Good
Rendering Pipeline
JWT verification middleware runs before the server sends a response, affecting the time to first byte and interaction readiness.
Request Processing
Response Generation
⚠️ BottleneckToken verification CPU cost can delay response generation.
Core Web Vital Affected
INP
This affects the server response time and user interaction speed by adding token verification before processing requests.
Optimization Tips
1Use asynchronous JWT verification to avoid blocking the server event loop.
2Cache decoded tokens when possible to reduce repeated verification cost.
3Avoid heavy synchronous operations in middleware to improve interaction responsiveness.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance impact of synchronous JWT verification middleware?
AIt improves browser rendering speed.
BIt reduces the size of the JWT token.
CIt blocks the event loop, increasing server response time.
DIt decreases network latency.
DevTools: Network
How to check: Open DevTools Network panel, inspect API request timing, and check 'Waiting (TTFB)' time for token verification delays.
What to look for: Long TTFB indicates blocking token verification; shorter TTFB means efficient middleware.