Fixed middleware troubles.
Started moving shared code into utils.