title: Flask how to redirect to previous page after successful login
body: <p>I have a webapp where I don't use Flask-login. If user visit a link and is not logged in, I redirect the user to login page. I achieve this my setting 'username' in session and checking that when user tries to access some link directly without logging in i.e in that case username will be null. </p>
  
  <p>I have tried to follow this<a href="https://stackoverflow.com/questions/3686465/flask-werkzeug-how-to-return-previous-page-after-login"> SO solution</a>, but the next parameter is always None. I have tried both solution but can't get either one to work. </p>
  
  <pre><code>username = session.get('username')
  if username:
      # go to home 
  else:
      next_url = request.url
      login_url = '%s?next=%s' % (url_for('login'), next_url)
      return redirect(login_url)
  </code></pre>
  
  <p>Second solution</p>
  
  <pre><code>username = session.get('username')
  if username:
      # go to home 
  else:
      return redirect(url_for('login', next= request.url))
  </code></pre>
  
  <p>print (request.url) = localhost:5000/visitPage</p>
  
  <p>Login Function</p>
  
  <pre><code>   if 'next' in request.args:
       return redirect(next)
     else:
       return redirect(url_for("user.index"))
  </code></pre>
  
  <p>Here when I  print (next), it is None <br>
  But login url has next argument</p>
  
  <blockquote>
    <p><a href="http://localhost:5000/login?next=http%3A%2F%2Flocalhost%3A5000%2FvisitPage" rel="noreferrer">http://localhost:5000/login?next=http%3A%2F%2Flocalhost%3A5000%2FvisitPage</a></p>
  </blockquote>