How to correctly use the next parameter in login and logout in Flask

Here is a sample login and logout route taken from the shopyo web framework. You can learn here how is get_safe_redirect defined and why it is important

@auth_blueprint.route("/login", methods=["GET", "POST"])
def login():
    context = {}
    login_form = LoginForm()
    context["form"] = login_form
    if login_form.validate_on_submit():
        email =
        password =
        user = User.query.filter(
            func.lower( == func.lower(email)
        if user is None or not user.check_password(password):
            flash(notify_danger("please check your user id and password"))
            return redirect(url_for("auth.login"))
        if 'next' not in request.form:
            next_url = url_for('dashboard.index')

            if request.form['next'] == '':
                next_url = url_for('dashboard.index')
                next_url = get_safe_redirect(request.form['next'])
        return redirect(next_url)
    return render_template("auth/login.html", **context)

@auth_blueprint.route("/logout", methods=["GET"])
def logout():
    flash(notify_success("Successfully logged out"))

    if 'next' not in request.args:
        next_url = url_for('dashboard.index')
        if request.args.get('next') == '':
            next_url = url_for('dashboard.index')
            next_url = get_safe_redirect(request.args.get('next'))
    return redirect(next_url)

The trick is adding this html snippet in your login form

    value="{{ request.args.get('next', '') }}"

1 thought on “How to correctly use the next parameter in login and logout in Flask”

  1. This design is steller! You obviously know how to keep a reader amused. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Excellent job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool!

Leave a Comment

Your email address will not be published. Required fields are marked *