Session context
Session context is a running session's cookies and storage, as a JSON object that you export and keep yourself. You pass it to a new session, which starts with the same cookies and storage, and so with the same logins. Use session context when your application must hold the state itself, for example in its own database. Browser state compares it with a profile, which Steel stores for you, and credentials, which sign in for your agent.
Session context works for sites that keep the login in cookies, localStorage, sessionStorage or IndexedDB. The new session restores a site's storage when it opens a page on that site.
Before you begin
Put your Steel API key in the STEEL_API_KEY environment variable. Then install the Steel SDK and Playwright.
npm install steel-sdk playwrightpython3 -m venv .venv
source .venv/bin/activate
pip install steel-sdk playwrightExport the context
Call client.sessions.context with the session's ID. You can export the context only while the session runs, so export it before you release the session.
This program signs in to Steel's practice site, exports the context to context.json, and releases the session. Set SITE_USERNAME and SITE_PASSWORD to the test login that the site's sign-in page shows.
import { writeFile } from "node:fs/promises";
import Steel from "steel-sdk";
import { chromium } from "playwright";
const client = new Steel();
const session = await client.sessions.create();
try {
const browser = await chromium.connectOverCDP(session.websocketUrl);
const browserContext = browser.contexts()[0];
const page = browserContext.pages()[0] ?? (await browserContext.newPage());
await page.goto("https://steel.dev/practice/login");
await page.fill('input[name="username"]', process.env.SITE_USERNAME!);
await page.fill('input[name="password"]', process.env.SITE_PASSWORD!);
await page.click('button[type="submit"]');
await page.waitForURL("**/secure");
const context = await client.sessions.context(session.id);
await writeFile("context.json", JSON.stringify(context));
console.log(`Saved ${context.cookies?.length ?? 0} cookies`);
await browser.close();
} finally {
await client.sessions.release(session.id);
}import json
import os
from pathlib import Path
from playwright.sync_api import sync_playwright
from steel import Steel
client = Steel()
session = client.sessions.create()
try:
with sync_playwright() as playwright:
browser = playwright.chromium.connect_over_cdp(session.websocket_url)
browser_context = browser.contexts[0]
page = browser_context.pages[0] if browser_context.pages else browser_context.new_page()
page.goto("https://steel.dev/practice/login")
page.fill('input[name="username"]', os.environ["SITE_USERNAME"])
page.fill('input[name="password"]', os.environ["SITE_PASSWORD"])
page.click('button[type="submit"]')
page.wait_for_url("**/secure")
context = client.sessions.context(session.id)
Path("context.json").write_text(json.dumps(context.to_dict(mode="json")))
print(f"Saved {len(context.cookies or [])} cookies")
browser.close()
finally:
client.sessions.release(session.id)Run the program:
npx tsx export-context.mtspython export_context.pyThe program writes the context to context.json and prints how many cookies it holds. The next section reads that file, and What a context holds describes its fields.
Saved 1 cookiesTo save a login, sign in during this session, with your code or by hand in the live view. Before you export the context, open a page that only a signed-in user can see, to check that the login worked.
Start a session with a context
Pass the context in sessionContext when you create the session. Without sessionContext, a session starts with an empty context.
This program reads context.json, starts a session with it, and opens a page that only a signed-in user can see.
import { readFile } from "node:fs/promises";
import Steel from "steel-sdk";
import { chromium } from "playwright";
const client = new Steel();
const sessionContext = JSON.parse(await readFile("context.json", "utf8"));
const session = await client.sessions.create({ sessionContext });
try {
const browser = await chromium.connectOverCDP(session.websocketUrl);
const context = browser.contexts()[0];
const page = context.pages()[0] ?? (await context.newPage());
await page.goto("https://steel.dev/practice/secure");
console.log(page.url());
await browser.close();
} finally {
await client.sessions.release(session.id);
}import json
from pathlib import Path
from playwright.sync_api import sync_playwright
from steel import Steel
client = Steel()
session_context = json.loads(Path("context.json").read_text())
session = client.sessions.create(session_context=session_context)
try:
with sync_playwright() as playwright:
browser = playwright.chromium.connect_over_cdp(session.websocket_url)
context = browser.contexts[0]
page = context.pages[0] if context.pages else context.new_page()
page.goto("https://steel.dev/practice/secure")
print(page.url)
browser.close()
finally:
client.sessions.release(session.id)Run the program:
npx tsx use-context.mtspython use_context.pyThe program prints the page's URL. The new session is signed in, so the site shows the page. Without the context, the site sends the browser to its sign-in page.
https://steel.dev/practice/secureA context is a copy from one moment. What the new session changes does not reach your context.json. To keep the new state, export the context again before you release the session.
A site can still ask for a new login, for example when the login has expired or when the account appears from a new IP address. Like a profile, a context does not keep the address. Profiles explains how to keep it with a dedicated IP.
Check that it worked
Run the program in Start a session with a context. It prints https://steel.dev/practice/secure, so the site accepts the login from context.json. To see the difference, remove sessionContext (session_context in Python) from the program and run it again. That session has no login, so the program prints the sign-in page's URL, https://steel.dev/practice/login.
What a context holds
| Field | What it holds |
|---|---|
cookies | A list of cookies. Each cookie has a name and a value, and can have domain, path, expires, httpOnly, secure, sameSite and other attributes. |
localStorage | The localStorage items, grouped by domain: an object that maps each domain to its keys and values. |
sessionStorage | The sessionStorage items, grouped by domain in the same way. |
indexedDB | The IndexedDB databases, grouped by domain: for each domain, a list of databases with their object stores and records. |
You can edit the object before you pass it, for example to remove a site's cookies. A context does not hold the rest of the browser, such as its extensions, settings or history. For those, use a profile. The Sessions API has the full schema.
Troubleshooting
Session is not live, so its context cannot be read
{
"error": "Not Found",
"message": "Session 'SESSION_ID' is not live, so its context cannot be read. Context is only available while a session is running — create a new session or check its status first.",
"retryable": false,
"linkToDocs": "https://docs.steel.dev/overview/sessions-api/session-lifecycle"
}Cause: The session has ended. Steel does not keep a released session's context.
Fix: Export the context before you release the session, as the program in Export the context does. If the session ended on its timeout, set a longer timeout.
Verify: client.sessions.context returns an object with cookies.
Next steps
- Credentials: Sign in again when the cookies in a context no longer work.