This middleware duplicates the other middleware on line 31 almost exactly, with line 71 being the one critical difference.  Maybe we can combine the two?