Split functionality into three middleware functions