Updated middleware logic