title: Middleware in flask
body: <p>I just stated using Flask and was trying to implement a small feature in my project. The objective is to set a cookie only if the request comes from a authenticated user.</p>
  
  <p>I found two ways of doing this. </p>
  
  <p>First method</p>
  
  <pre><code>@app.before_request
  def before_request():
     # set cookie if user is logged in
  </code></pre>
  
  <p>Second method, by implementing something like this 
  <a href="https://ohadp.com/adding-a-simple-middleware-to-your-flask-application-in-1-minutes-89782de379a1#.xq8zafufd" rel="noreferrer">adding-a-simple-middleware-to-your-flask-application</a></p>
  
  <p>Can someone explain to me what are the main differences between the two methods and when and where which method should be used.</p>
  
  <p>Also, I am currently using "flask-login" to keep track of the logged in user.
  If I use the first method, I can easily verify if someone is logged in by importing the current_user</p>
  
  <pre><code>from flask.ext.login import current_user
  </code></pre>
  
  <p>but if I try to do the same while using the second method, the current_user is always "None" as the application context is incorrect.</p>
  
  <p>So, I wanted to know if I decided to go ahead with the second implementation, how do I check if the user is logged in or not.</p>