Skip to content

Protecting Routes (@login_required)

To protect a route so only logged-in users can access it:

python
from flask_login import login_required
 
 
@app.route("/dashboard")
@login_required
def dashboard():
    return "Secret dashboard"

If a user is not logged in, Flask-Login will:

  • redirect them to login_view
diagram what @login_required does on every request mermaid
The decorator runs before your view function, so an unauthenticated request never reaches your code. Flask-Login stores where the user was trying to go, which is what makes the redirect after login land in the right place instead of on the home page.
python
login_manager.login_view = "login"

Now anonymous users are redirected to /login.

Flask-Login often preserves the originally requested URL via a next parameter.

Your login view can redirect back to it after successful login.

Be careful:

  • validate next is a safe local URL (avoid open redirects)

Inside protected routes, you can use:

python
from flask_login import current_user
 
current_user.id
current_user.is_authenticated

This is how you tailor pages to the logged-in user.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading