Tidy middleware and configuration

Removed some duplicated code and turned some floating functions into proper express middleware to simplify things a bit.