ryer.io

Solving the Expired Token Middleware Issue

TL;DR

  • Encountered a silent failure when handling expired JWT tokens.
  • Identified the issue was with how the Malter error handler processed errors.
  • Solution involved separating JWT error handling from Malter to ensure proper middleware flow.
  • Implemented enhanced checks for token errors.

I recently encountered a perplexing issue where the middleware handling for expired JWT tokens didn’t provide any log output indicating a failure. This issue occurred in an Express.js application when the admin JWT check failed, and it was hard to trace due to insufficient log details.

The Mystery

Initially, I noticed a server error status without any clear logging. The core of the issue was how errors were processed using a built-in responses object, which didn’t log the error properly. My task was to figure out why expired token errors were being wrapped incorrectly and without informative logs.

The Investigation

I began by scrutinizing where responses.serverError was called, narrowing down the references. I added console logs and switched to a default logger to trace potential output points, but they yielded no results.

Then, using Postman, I noticed that the response status was “failure” and related this back to the server’s exported functions. My tracing led me to a Malter error handler, crucial for file uploads, which seemed to mishandle the JWT error.

The Discovery

JWT token errors were being caught too late, specifically by the Malter error handler intended for file-related errors. It improperly categorized them as server errors, resulting in misleading 500 responses.

The Solution

The naive solution would have been to check for the JWT error in the Malter handler, but I realized it should have been pre-filtered out in the JWT check middleware itself. So, I decided to:

  • Ensure any token errors were caught before hitting the Malter handler.
  • Allow non-relevant errors to pass through to subsequent middleware for proper handling.
  • Enhanced the JWT error middleware using additional name and message checks to comprehensively detect expired tokens.

Outcome

After implementing these changes and performing tests, the adjustments worked as intended. JWT errors were properly handled without misclassification, and clear logs were produced for more efficient debugging in the future.

This was a valuable exercise in maintaining clear boundaries between different error handlers and ensuring robust middleware flow in an Express.js application.