Adding custom data to middleware response in laravel 9 or 10 php

I want to implement a user tracking system, after searching I realized that I have to do this in the middleware. The problem I had was that I could only add values to the response header in the answers that were in the middleware. And after saving their information, delete them in the middleware response. Please guide me how to add custom data to the middleware response, thanks

For this, I found 2 examples that work in json mode, but in the case that I want to transfer the user to the route, I have to use headers.

Sample code for json response:

return $response->json([
                    'status' => $status,
                    'code' => $code,
                    'errors' => [$errors],
                ], $status);