How do you handle authentication and correlation IDs across Node microservices?
Topic: microservices, Node Side. Level: Intermediate.
Answer
Validate a JWT at the gateway/service (verify signature, issuer, audience, expiry) and forward the user context downstream. Generate or adopt a correlation id per request, attach it to logs (structured, e.g. `pino`), and forward it on outbound calls so a request can be traced across services.
```js
// middleware: adopt/create correlation id + verify JWT, forward both downstream
app.use((req, res, next) => {
req.cid = req.headers['x-correlation-id'] ?? crypto.randomUUID()
res.setHeader('x-correlation-id', req.cid)
req.user = jwt.verify(bearer(req), publicKey, { issuer, audience })
next()
})
// outbound call reuses them:
fetch(url, { headers: { 'x-correlation-id': req.cid, authorization: req.headers.authorization } })
```