Rewrite the middleware and add tests