Refactor Middleware

Change the middleware flow