move middleware into a function