refactor of some middleware stuff