Skip to content

User Loader Function

Flask-Login stores a user id in the session.

On the next request, it needs to turn that id into a User object.

That’s what the user loader does.

diagram the user_loader runs once per request, not once per login mermaid
The session only stores an id. On every single request Flask-Login takes that id and calls your user_loader to turn it back into a user object -- which is why the function must be cheap, and why returning None for a deleted user is what logs them out.
python
from flask_login import LoginManager
 
login_manager = LoginManager()
 
 
@login_manager.user_loader
def load_user(user_id: str):
    return User.query.get(int(user_id))
  • user_id comes from the session, so it’s a string.
  • Convert types carefully.
  • Return None if the user doesn’t exist.
  • Forgetting to register the loader → Flask-Login can’t restore sessions
  • Querying with the wrong type
  • Returning something that isn’t a User model/UserMixin

In larger apps, user loader registration usually lives in:

  • auth blueprint
  • app factory initialization

So it’s registered exactly once.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading