Identifying Express middleware
Debugging middleware in Express apps isn’t always straightforward. Middleware can be applied to the entire app, specific routes, and/or specific methods. The order that middleware is executed for any given request is not always clear, either. Long-running and/or blocking middleware can frequently be the cause of performance bottlenecks, so knowing their duration is important.
Middleware timing data
Glimpse makes it easier to visualize all of these important aspects of your app’s middleware. To view timing information for middleware:
- Navigate to the Timeline tab.
- Scroll down to the events table below the timeline, which will include the duration and offsets for all executed middleware for the selected request.
The Three slowest events are shown above the timeline, which gives you quick access to potentially slow middleware by clicking their links in this section.
You can also view how request metadata was transformed in each middleware:
- Navigate to the Request tab.
- Scroll down to the Application middleware section.
There are a few ways to optimize middleware to improve request performance, and also to make it easier to debug your application.
- Remove unused middleware. Though Glimpse won’t tell you if a middleware is “unused,” it will allow you to easily identify potentially unnecessary middleware, and show you where that middleware is being called. This makes it easier to refactor and be more selective about middleware inclusion.
- Add helpful middleware. The middleware tables surfaced by Glimpse make it readily apparent if you forgot to add any helpful middleware, such as
compressionor any caching middleware.
- Identify anonymous middleware. Sometimes, middleware will appear as
Middleware | [anonymous], which isn’t exactly helpful. Consider using named functions instead of anonymous functions when defining middleware for easier debugging.
More tips and best practices can be found in the Express docs.
Middle-where did that happen?
Don’t know where or why a certain middleware was executed? The Location column shows you the exact line and column where the middleware was defined. If you’re using Visual Studio Code, clicking the link will take you directly to that location. This is especially useful for identifying anonymous middleware.