2022-05-16 Two simple helpers for debugging Express.js applications

Sometimes, when debugging Express.js applications, it happens that one of the many middlewares for some route is misbehaving and either redirects to somewhere it shouldn’t, hangs or something like this, resulting in a 500. While it is possible to attach a debugger to Node.js, a good ol’ console.log is often an easy and fast way to find a culprit. Especially with this very simple middleware:

function debug_message_middleware(message) {
    return (req, res, next) => {
	return next();

You can then use it like this:

    debug_message_middleware('after middleware 1'),
    debug_message_middleware('after middleware 2'),
    debug_message_middleware('after middleware 3'),

and now, if you see after middleware 1 and after middleware 2 but not after middleware 3 on your console, you know that middeware_3 is the one acting funny. (By the way, if you want to golf this code a bit – and be a little fancy and a little more functional – you could use the comma operator between console.warn and next. Just remember that it ties more weakly than the fat function syntax – here is one of the entries to that rabbit hole – so you need an additional pair of parentheses, like in () => (f(), g()).)

Speaking of debugging helpers, I was recently working on an app where the front-end was issuing some ajax requests to the server, and I wanted to see what happens if the server takes its time to answer them. Of course, during local development I had everything on my laptop, so the server response was nearly instantaneous. While Firefox devtools have a “throttle” feature, it was next to useless for me – it slows down all the network operations, including the initial loading of the (pretty big) blob with all the JavaScript doing the front-end stuff, and I didn’t want to wait that long. I decided to do things differently and perform the slowdown myself, directly on the server, and came up with this:

function debug_wait_middleware(milliseconds) {
    return (req, res, next) => setTimeout(next, milliseconds);

And now I can just insert debug_wait_middleware(1000) before the controller to make it wait about a second instead of responding at once.

That’s it for today!

CategoryEnglish, CategoryBlog, CategoryJavaScript