Caching User Credentials

If you have an automation that requires logging into a site, you can save time by securely caching and passing your credentials.

Overview

This guide shows how to avoid logging into the website multiple times by caching user credentials with AgentQL.

Cache user credentials

After logging into a site, you need to save all relevant authentication cookies and local storage with the storage_state() method.

Here's an example of saving the current browser session to a local file called session.json.

cache_user_credentials.py
python
browser.contexts[0].storage_state(path="session.json")

Here is the complete script that saves your current session with the website into a local file for future use authenticating sessions:

cache_user_credentials.py
python
import agentql
from playwright.sync_api import sync_playwright

URL = "WEBSITE_URL"
EMAIL = "YOUR_EMAIL"
PASSWORD = "YOUR_PASSWORD"

with sync_playwright() as p, p.chromium.launch(headless=False) as browser:
    page = agentql.wrap(browser.new_page())
    page.goto(URL)

    log_in_query = """
    {
        sign_in_form {
            email_input
            password_input
            log_in_btn
        }
    }
    """

    aql_response = page.query_elements(log_in_query)
    # Fill the email and password input fields
    response_credentials.sign_in_form.email_input.fill(EMAIL)
    response_credentials.sign_in_form.password_input.fill(PASSWORD)
    response_credentials.sign_in_form.log_in_btn.click()

    page.wait_for_page_ready_state()

    # Wait for session to be updated with latest credentials
    page.wait_for_timeout(5000)

    # Save the signed-in session
    browser.contexts[0].storage_state(path="yelp_login.json")

Load user credentials

To load the session that was saved to a local file, start a new browser context with the path of the session file from cache user credentials as an argument with the new_context() method.

load_user_credentials.py
python
browser.new_context(storage_state="session.json")

Here is a complete script that loads the saved session:

cache_user_credentials.py
python
import agentql
from playwright.sync_api import sync_playwright

with sync_playwright() as playwright, playwright.chromium.launch(headless=False) as browser:
    # Load the saved signed-in session by creating a new browser context with the saved session
    context = browser.new_context(storage_state="session.json")

    page = agentql.wrap(context.new_page())

    page.goto(URL)

    page.wait_for_page_ready_state()

    # Used only for demo purposes. It allows you to see the effect of the script.
    page.wait_for_timeout(10000)

Conclusion

Now that you understand how to save a session and load it in future sessions, you can enhance your workflows by caching and passing authetication credentials.