Can you move this into a separate middleware function? We should start adding tests too, but in leiu of that we can just separate out each thing that does something differently.