Bird
Raised Fist0
Flaskframework~8 mins

Remember me functionality in Flask - Performance & Optimization

Choose your learning style10 modes available
Performance: Remember me functionality
MEDIUM IMPACT
This affects page load speed and interaction responsiveness by managing persistent login states and cookie handling.
Implementing persistent login with 'remember me' in Flask
Flask
from flask import Flask, request, redirect, make_response
from itsdangerous import URLSafeTimedSerializer
app = Flask(__name__)
serializer = URLSafeTimedSerializer('secret-key')

@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    resp = make_response(redirect('/'))
    if 'remember' in request.form:
        token = serializer.dumps(username)
        resp.set_cookie('remember_token', token, max_age=60*60*24*30, httponly=True, secure=True, samesite='Lax')
    else:
        resp.set_cookie('remember_token', '', expires=0)
    return resp
Uses encrypted token with limited max_age and secure cookie flags to reduce cookie size and improve security, minimizing blocking and improving responsiveness.
📈 Performance GainReduces cookie size and network payload; avoids blocking rendering; improves interaction speed.
Implementing persistent login with 'remember me' in Flask
Flask
from flask import Flask, request, redirect, make_response
app = Flask(__name__)

@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    resp = make_response(redirect('/'))
    if 'remember' in request.form:
        resp.set_cookie('user', username, max_age=60*60*24*365)  # 1 year
    else:
        resp.set_cookie('user', username)
    return resp
Sets cookies without secure flags and uses long max_age without encryption, causing security risks and potential unnecessary cookie size.
📉 Performance CostAdds unencrypted cookie data increasing network payload; can block rendering if cookie size grows large.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Unencrypted large cookieNone0Minimal[X] Bad
Encrypted small token cookieNone0Minimal[OK] Good
Rendering Pipeline
Remember me functionality mainly affects the network and scripting stages by adding cookies that the browser sends with requests and scripts that read them to restore sessions.
→Network
→Scripting
→Rendering
⚠️ BottleneckNetwork latency and scripting time to validate and parse cookies
Core Web Vital Affected
INP
This affects page load speed and interaction responsiveness by managing persistent login states and cookie handling.
Optimization Tips
1Use encrypted tokens instead of plain user data in cookies.
2Set secure, HttpOnly, and SameSite flags on remember me cookies.
3Limit cookie max_age to balance persistence and network overhead.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a key performance benefit of using encrypted tokens for 'remember me' cookies?
AIncreases cookie size for better security
BAllows storing plain user data for faster access
CSmaller cookie size reduces network payload and speeds up requests
DDisables browser caching to improve freshness
DevTools: Network
How to check: Open DevTools, go to Network tab, reload page, and inspect request headers for cookie size and flags.
What to look for: Look for cookie size under request headers and presence of secure, httponly, and samesite flags.

Practice

(1/5)
1. What does the remember=True parameter do when used with login_user() in Flask-Login?
easy
A. Logs the user out immediately after login.
B. Deletes the user's account after login.
C. Prevents the user from logging in.
D. Keeps the user logged in across browser sessions using cookies.

Solution

  1. Step 1: Understand the purpose of remember=True

    This parameter tells Flask-Login to store a cookie that keeps the user logged in even after closing the browser.
  2. Step 2: Compare with other options

    Options A, C, and D describe actions that do not relate to keeping the user logged in across sessions.
  3. Final Answer:

    Keeps the user logged in across browser sessions using cookies. -> Option D
  4. Quick Check:

    Remember me = persistent login [OK]
Hint: Remember me means stay logged in after closing browser [OK]
Common Mistakes:
  • Thinking remember=True logs out user
  • Confusing remember with user registration
  • Assuming remember deletes user data
2. Which of the following is the correct way to enable 'remember me' when logging in a user in Flask?
easy
A. login_user(user, remember=1)
B. login_user(user, remember='yes')
C. login_user(user, remember=True)
D. login_user(user, remember='false')

Solution

  1. Step 1: Check the correct parameter type

    The remember parameter expects a boolean value, so True is correct.
  2. Step 2: Analyze other options

    Options A, B, and D use integer or string instead of boolean, which is incorrect. login_user(user, remember='false') uses string 'false' which is not boolean False.
  3. Final Answer:

    login_user(user, remember=True) -> Option C
  4. Quick Check:

    Boolean True enables remember me [OK]
Hint: Use boolean True for remember parameter [OK]
Common Mistakes:
  • Passing strings instead of boolean
  • Using numbers instead of boolean
  • Using 'false' string instead of False
3. Given this Flask code snippet:
from flask_login import login_user

user = get_user()
login_user(user, remember=True)

What will happen if the user closes and reopens the browser?
medium
A. The user will remain logged in automatically.
B. The user will be logged out immediately.
C. The user will see an error message.
D. The user must log in again manually.

Solution

  1. Step 1: Understand the effect of remember=True

    This stores a cookie that keeps the user logged in even after browser restart.
  2. Step 2: Predict user state after reopening browser

    Because of the cookie, the user session persists, so the user stays logged in automatically.
  3. Final Answer:

    The user will remain logged in automatically. -> Option A
  4. Quick Check:

    Remember me keeps session after browser close [OK]
Hint: Remember me means no login needed after browser restart [OK]
Common Mistakes:
  • Assuming user is logged out after closing browser
  • Expecting error on reopening browser
  • Confusing remember with session timeout
4. What is wrong with this Flask code snippet for 'remember me' functionality?
login_user(user, remember='True')
medium
A. The user variable is not defined.
B. The remember parameter should be a boolean, not a string.
C. login_user does not accept a remember parameter.
D. The code is correct and will work as expected.

Solution

  1. Step 1: Check parameter type for remember

    The remember parameter must be a boolean value, not a string.
  2. Step 2: Validate other options

    User variable is assumed defined; login_user accepts remember; so only parameter type is wrong.
  3. Final Answer:

    The remember parameter should be a boolean, not a string. -> Option B
  4. Quick Check:

    remember must be True/False boolean [OK]
Hint: Use True without quotes for remember [OK]
Common Mistakes:
  • Passing 'True' as string instead of boolean
  • Forgetting to define user variable
  • Assuming remember is unsupported
5. You want to implement a logout button that clears the 'remember me' session in Flask. Which code snippet correctly logs out the user and clears the remembered login?
hard
A. from flask_login import logout_user logout_user()
B. from flask_login import logout_user logout_user(remember=False)
C. from flask_login import logout_user logout_user(user)
D. from flask_login import logout_user logout_user(clear=True)

Solution

  1. Step 1: Understand logout_user behavior

    Calling logout_user() clears the user session and any remember me cookies automatically.
  2. Step 2: Analyze other options

    logout_user does not take parameters like remember, user, or clear; these cause errors or are ignored.
  3. Final Answer:

    from flask_login import logout_user logout_user() -> Option A
  4. Quick Check:

    logout_user() clears session and remember me [OK]
Hint: Use logout_user() without parameters to clear remember me [OK]
Common Mistakes:
  • Passing parameters to logout_user()
  • Not calling logout_user to clear remember me
  • Assuming remember must be cleared separately
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard