[944486] Refactored middleware to condense code

ref: https://bugzilla.mozilla.org/show_bug.cgi?id=944486