Skip to content

Add request ID middleware and correlate logs with request context#58

Merged
prodbycorne merged 1 commit into
SmartDropLabs:mainfrom
Jennylila:fix/request-id-middleware
Jun 27, 2026
Merged

Add request ID middleware and correlate logs with request context#58
prodbycorne merged 1 commit into
SmartDropLabs:mainfrom
Jennylila:fix/request-id-middleware

Conversation

@Jennylila

Copy link
Copy Markdown
Contributor

Overview

This PR adds request ID middleware and AsyncLocalStorage-backed log correlation so concurrent request logs can be traced through the system. Every incoming request gets a UUID, returned via X-Request-ID, and all log lines within that request automatically include the matching requestId.

Related Issue

Closes #34

Changes

🔗 Request ID Middleware

  • [ADD] src/middleware/requestId.js
  • Generates a UUID for every incoming request using crypto.randomUUID().
  • Attaches the ID to req.id and sets the X-Request-ID response header.
  • Runs downstream handlers inside AsyncLocalStorage so child log calls inherit request context without passing req manually.

📝 Logger Correlation

  • [MODIFY] src/logger.js
  • Added a Winston format that reads requestId from AsyncLocalStorage on every log line.
  • Logs outside an active request context use requestId: 'system' (background jobs, startup, shutdown).

🚀 App Wiring

  • [MODIFY] src/index.js
  • Registered requestIdMiddleware early in the Express middleware chain.
  • Fixed module export so server is defined when the app is imported in tests.

🧪 Tests

  • [ADD] test/requestId.test.js
  • Verifies X-Request-ID is present on responses.
  • Verifies req.id matches the response header.
  • Verifies AsyncLocalStorage context propagation.
  • Verifies log output includes the matching requestId for a given request.
  • Verifies background tasks log with requestId: 'system'.
  • Verifies /health returns X-Request-ID.

🔧 Configuration

  • [MODIFY] package.json
  • Fixed a missing comma that prevented npm install from parsing dependencies.

Verification Results

npm test -- test/requestId.test.js ✅ passed (6/6)
Acceptance Criteria Status
X-Request-ID header on every response
Request ID propagated to all log lines within that request
Background tasks log with requestId: 'system'
Test: log output includes matching requestId for a given request
ALS used (not req passed manually through every function)

Generate a UUID per request, expose it via X-Request-ID, and propagate it to all log lines through AsyncLocalStorage so concurrent requests can be traced in production.
@prodbycorne prodbycorne merged commit 5b73b5f into SmartDropLabs:main Jun 27, 2026
1 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add request ID middleware and correlate logs with request context

2 participants