Access middleware to the variable on the page

I have the page with the variable. The variable will be the name of the user. I want to create a middleware that get a cookie, connects to the database, gets a user name and fills the variable. I don’t know how the middleware would get access to the variable. Maybe I do this in a wierd way )))