Query handling middleware