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.

Example

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))
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))

Important notes

  • user_iduser_id comes from the session, so it’s a string.
  • Convert types carefully.
  • Return NoneNone if the user doesn’t exist.

Common pitfalls

  • 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

Where to put this code

In larger apps, user loader registration usually lives in:

  • authauth blueprint
  • app factory initialization

So it’s registered exactly once.

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did