Reusing Context & Auth
How to Reuse Authentication Across Steel Sessions
The Steel Sessions API provides a contexts endpoint that allows you to capture and transfer browser state (including cookies and local storage) between sessions. This is particularly useful for maintaining authenticated states across multiple sessions, helping your AI agents access protected resources efficiently without repeatedly handling login processes or exposing credentials at all.
In this guide, you'll learn how to use the Steel Sessions API to reuse authentication between browser sessions.
For an easier way to reuse authentication, context, cookies, extensions etc. consider using Steel's new Profiles API. It utilizes auth context alongside a complete browser profile to automatically reuse all your auth, not just context or cookies.
For additional practical examples and recipes, check out the Steel Cookbook.
Prerequisites
-
Steel API Key
-
Steel SDK installed.
$npm install steel-sdk
- Familiarity with Steel sessions
Overview of the Process
Reusing authentication across sessions involves a straightforward workflow:
-
Create and authenticate an initial session. Create a Steel session, navigate to target websites, and authenticate (log-in, etc).
-
Capture the session context. Extract browser state data through the
GET /v1/sessions/{id}/contextendpoint. This endpoint returns a context object containing browser state information such as cookies and local storage. Example:Typescript1const initialSessionContext = await client.sessions.context(initialSession.id); -
Reuse session context in new sessions. Create new sessions using the captured context object by passing it directly to the
sessionContextparameter. Example:Typescript1const session = await client.sessions.create({ sessionContext: initialSessionContext });Now your new session will begin with the same authenticated state as your previous session without having to manually authenticate again.
Complete Example (Playwright, Node.js)
Note: While this example uses TypeScript, Node.js, and Playwright, the same logic applies regardless of your programming language or automation framework. The Steel API handles the context management - you just need to capture and reuse it using your preferred tools.
The following script demonstrates the entire authentication reuse process. It:
-
Creates an initial session and authenticates with a webesite by logging in
-
Captures the authenticated session context
-
Creates a new session using the captured context
-
Verifies the authentication was successfully transferred to the new session
1import { chromium, Page } from "playwright";2import Steel from "steel-sdk";3import dotenv from "dotenv";45dotenv.config();67const client = new Steel({8steelAPIKey: process.env.STEEL_API_KEY,9});1011// Helper function to perform login12async function login(page: Page) {13await page.goto("https://practice.expandtesting.com/login");14await page.fill('input[name="username"]', "practice");15await page.fill('input[name="password"]', "SuperSecretPassword!");16await page.click('button[type="submit"]');17}1819// Helper function to verify authentication20async function verifyAuth(page: Page): Promise<boolean> {21await page.goto("https://practice.expandtesting.com/secure");22const welcomeText = await page.textContent("#username");23return welcomeText?.includes("Hi, practice!") ?? false;24}2526async function main() {27let session;28let browser;2930try {31// Step 1: Create and authenticate initial session32console.log("Creating initial Steel session...");33session = await client.sessions.create();34console.log(35`\x1b[1;93mSteel Session #1 created!\x1b[0m\n` +36`View session at \x1b[1;37m${session.sessionViewerUrl}\x1b[0m`37);3839// Connect Playwright to the session40browser = await chromium.connectOverCDP(41`wss://connect.steel.dev?apiKey=${process.env.STEEL_API_KEY}&sessionId=${session.id}`42);4344const page = await browser.contexts()[0].pages()[0];45await login(page);4647if (await verifyAuth(page)) {48console.log("✓ Authentication successful");49}5051// Step 2: Capture and transfer authentication52const sessionContext = await client.sessions.context(session.id);5354// Clean up first session55await browser.close();56await client.sessions.release(session.id);57console.log("Session #1 released");5859// Step 3: Create new authenticated session6061session = await client.sessions.create({ sessionContext });62console.log(63`\x1b[1;93mSteel Session #2 created!\x1b[0m\n` +64`View session at \x1b[1;37m${session.sessionViewerUrl}\x1b[0m`65);6667// Connect to new session68browser = await chromium.connectOverCDP(69`wss://connect.steel.dev?apiKey=${process.env.STEEL_API_KEY}&sessionId=${session.id}`70);7172// Verify authentication transfer73const newPage = await browser.contexts()[0].pages()[0];74if (await verifyAuth(newPage)) {75console.log("\x1b[32m✓ Authentication successfully transferred!\x1b[0m");76}77} catch (error) {78console.error("Error:", error);79} finally {80// Cleanup81await browser?.close();82if (session) {83await client.sessions.release(session.id);84console.log("Session #2 released");85}86}87}8889main().catch(console.error);
Check out the full example
Important Considerations
-
Cookie and JWT Based Authentication Only: This method works exclusively with websites that utilize cookie-based or JWT-based authentication (saved onto Local Storage).
-
Enhancing Continuity: A useful practice is to save the URL of the last visited page along with the session context. This allows you to restore the browsing context, providing continuity for users.
-
Session Security: Treat captured contexts as sensitive data. Ensure proper security and regularly refresh your sessions to maintain account integrity.
-
Available for Live Sessions: Context can only be captures from live sessions. So if you wish to re-use a context, make sure to grab the object before releasing the session.