> ## Documentation Index
> Fetch the complete documentation index at: https://docs.browserbase.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Automated testing

> Run reliable end-to-end browser tests at scale with Browserbase. Automate login flows, UI validation, and regression testing using Stagehand or Playwright.

Run end-to-end browser tests in consistent, isolated cloud environments. Browserbase gives you reliable infrastructure for automated testing workflows, whether you're using Stagehand or Playwright.

* Reduce flaky tests with predictable, isolated browser sessions
* Debug failures with built-in [session replays](https://docs.browserbase.com/platform/browser/observability/session-replay.md) and [screenshots](https://docs.browserbase.com/platform/browser/files/screenshots.md)
* Scale test runs across [concurrent sessions](https://docs.browserbase.com/optimizations/concurrency/overview.md) without managing infrastructure
* Test from different locations and viewports with [proxies](https://docs.browserbase.com/platform/identity/proxies.md) and configurable browser settings

## Template

Get started quickly with a ready-to-use testing template.

> [card] [Website Link Tester](https://www.browserbase.com/templates/website-link-tester)
>
> Clone, configure, and run in minutes

## Example: Testing a login flow

To demonstrate automated testing with Browserbase, this example validates a login flow against a sample application.

### Code example

> [tab] Node.js
>
> ```typescript Node.js Stagehand theme={null}
> import { browserbase, Stagehand } from "@browserbasehq/stagehand";
> import { z } from "zod";
> import dotenv from "dotenv";
>
> async function main() {
>   dotenv.config();
>   const browser = await browserbase.launch({
>     apiKey: process.env.BROWSERBASE_API_KEY,
>   });
>   const stagehand = await Stagehand.create({ browser });
>   const [page] = await browser.context.pages();
>
>   async function automatedLoginTest(inputs: any) {
>     // Navigate to the form
>     await page.goto("https://www.saucedemo.com/");
>
>     await stagehand.act(`Input Username: ${inputs.username}`);
>     await stagehand.act(`Input Password: ${inputs.password}`);
>     await stagehand.act("Click Login Button");
>
>     // take a screenshot of the page
>     await page.screenshot({ path: "login_screenshot.png" });
>
>     // log the url
>     return page.url();
>   }
>
>   const response = await automatedLoginTest({
>     username: "standard_user",
>     password: "secret_sauce",
>   });
>   console.log(response);
>
>   // close the stagehand session
>   await stagehand.close();
>   await browser.close();
> }
>
> main().catch(console.error);
> ```
>
> ```typescript Node.js Playwright theme={null}
> import { chromium } from "playwright-core";
> import Browserbase from "@browserbasehq/sdk";
> import { config } from "dotenv";
> config();
>
> async function createSession() {
>   const bb = new Browserbase({ apiKey: process.env.BROWSERBASE_API_KEY! });
>   const session = await bb.sessions.create({
>     // Add configuration options here
>   });
>   return session;
> }
>
> async function automatedLoginTest(
>   page: any,
>   inputs: { url: string; username: string; password: string },
> ) {
>   // Navigate to page
>   await page.goto(inputs.url);
>
>   await page.locator('input[data-test="username"]').fill(inputs.username);
>   await page.locator('input[data-test="password"]').fill(inputs.password);
>   await page.locator('input[data-test="login-button"]').click();
>
>   // take a screenshot of the page
>   await page.screenshot({ path: "login_screenshot.png" });
>
>   // log the url
>   return page.url();
> }
>
> async function main() {
>   const session = await createSession();
>   const browser = await chromium.connectOverCDP(session.connectUrl);
>
>   // Getting the default context to ensure the sessions are recorded.
>   const defaultContext = browser.contexts()[0];
>   const page = defaultContext?.pages()[0];
>
>   console.log(
>     `View session replay at https://browserbase.com/sessions/${session.id}`,
>   );
>
>   // Test login flow
>   const loginResponse = await automatedLoginTest(page, {
>     url: "https://www.saucedemo.com/",
>     username: "standard_user",
>     password: "secret_sauce",
>   });
>   console.log(loginResponse);
>
>   console.log("Shutting down...");
>   await page.close();
>   await browser.close();
> }
>
> main();
> ```

> [tab] Python
>
> ```python Python Stagehand theme={null}
> import os
> import asyncio
> from stagehand import Stagehand, browserbase
> from dotenv import load_dotenv
>
> load_dotenv()
>
>
> async def main():
>     browser = await browserbase.launch(
>         api_key=os.environ["BROWSERBASE_API_KEY"]
>     )
>     stagehand = await Stagehand.create(browser=browser)
>     page = (await browser.context.pages())[0]
>
>     async def automated_login_test(inputs):
>         # Navigate to the form
>         await page.goto("https://www.saucedemo.com/")
>
>         await stagehand.act(f"Input Username: {inputs['username']}")
>         await stagehand.act(f"Input Password: {inputs['password']}")
>         await stagehand.act("Click Login Button")
>
>     await automated_login_test(
>         {
>             "username": "standard_user",
>             "password": "secret_sauce",
>         }
>     )
>
>     await stagehand.close()
>     await browser.close()
>
>
> if __name__ == "__main__":
>     asyncio.run(main())
> ```
>
> ```python Python Playwright theme={null}
> import os
> from playwright.async_api import async_playwright
> from browserbase import Browserbase
> from dotenv import load_dotenv
> import asyncio
>
> load_dotenv()
>
>
> async def create_session():
>     """Creates a Browserbase session."""
>     bb = Browserbase(api_key=os.environ["BROWSERBASE_API_KEY"])
>     session = bb.sessions.create(
>         # Add configuration options here if needed
>     )
>     return session
>
>
> async def automated_login_test(page, inputs):
>     """Automates login test, takes a screenshot, and returns the final URL."""
>     await page.goto(inputs["url"])
>
>     await page.locator('input[data-test="username"]').fill(inputs["username"])
>     await page.locator('input[data-test="password"]').fill(inputs["password"])
>     await page.locator('input[data-test="login-button"]').click()
>
>     # Take a screenshot
>     await page.screenshot(path="login_screenshot.png")
>
>     return page.url
>
>
> async def main():
>     async with async_playwright() as p:
>         session = await create_session()
>         print(
>             f"View session replay at https://browserbase.com/sessions/{session.id}"
>         )
>         browser = await p.chromium.connect_over_cdp(session.connect_url)
>
>         # Get the first context & page to access the session replay
>         context = browser.contexts[0]
>         page = context.pages[0]
>
>         # Run login automation
>         login_response = await automated_login_test(
>             page,
>             {
>                 "url": "https://www.saucedemo.com/",
>                 "username": "standard_user",
>                 "password": "secret_sauce",
>             },
>         )
>         print(f"Final URL after login: {login_response}")
>
>         # Take a screenshot of the page
>         await page.screenshot(path="login_screenshot.png")
>
>         # Add a wait for 5 seconds
>         await asyncio.sleep(5)
>
>         print("Shutting down...")
>         await page.close()
>         await browser.close()
>
>
> if __name__ == "__main__":
>     asyncio.run(main())
> ```

## Configuration options

### Set up a consistent environment

Set the same viewport dimensions for each test session.

> [tab] Node.js
>
> ```typescript Node.js theme={null}
> // Create a standardized session
> const session = await bb.sessions.create({
>   // Optional: Configure viewport size (desktop, mobile)
>   browserSettings: {
>     viewport: {
>       width: 1280,
>       height: 720,
>     },
>   },
> });
> ```

> [tab] Python
>
> ```python Python theme={null}
> # Create a standardized session
> session = bb.sessions.create(
>     # Optional: Configure viewport size (desktop, mobile)
>     browser_settings={
>         "viewport": {
>             "width": 1280,
>             "height": 720,
>         },
>     }
> )
> ```

### Test from different locations

Test how your app behaves from different locations:

> [tab] Node.js
>
> ```typescript Node.js theme={null}
> // Create a session with proxy support
> const session = await bb.sessions.create({
>   proxies: [
>     {
>       type: "browserbase",
>       geolocation: {
>         city: "New York",
>         state: "NY",
>         country: "US",
>       },
>     },
>   ],
> });
> ```

> [tab] Python
>
> ```python Python theme={null}
> # Create a session with proxy support
> session = bb.sessions.create(
>     proxies=[
>         {
>             "type": "browserbase",
>             "geolocation": {
>                 "city": "New York",
>                 "state": "NY",
>                 "country": "US",
>             },
>         },
>     ]
> )
> ```

### Complete configuration options

Set the viewport, operating system, and [full list of configuration options](https://docs.browserbase.com/reference/api/create-a-session.md) to customize your test environment.

## Best practices

### Record sessions

Every session is automatically recorded and available in the Browserbase dashboard. With [Session Replay](https://docs.browserbase.com/platform/browser/observability/session-replay.md), you can watch the exact session execution to debug failures efficiently.

> [tab] Node.js
>
> ```typescript Node.js theme={null}
> console.log(
>   `View session replay at https://browserbase.com/sessions/${session.id}`,
> );
> ```

> [tab] Python
>
> ```python Python theme={null}
> print(f"View session replay at https://browserbase.com/sessions/{session.id}")
> ```

**No extra setup required**: session replay is available automatically, allowing
you to diagnose flaky tests and failures with ease.

### Use metadata to organize tests

Add metadata for easier organization:

> [tab] Node.js
>
> ```typescript Node.js theme={null}
> const session = await bb.sessions.create({
>   userMetadata: {
>     testName: "login_flow",
>     suite: "authentication",
>   },
> });
> ```

> [tab] Python
>
> ```python Python theme={null}
> session = bb.sessions.create(
>     user_metadata={
>         "testName": "login_flow",
>         "suite": "authentication",
>     }
> )
> ```

### Capture screenshots

Capture screenshots at critical points for easier debugging.

> [tab] Node.js
>
> ```typescript Node.js theme={null}
> // Take a screenshot
> await page.screenshot({ path: "login_screenshot.png" });
> ```

> [tab] Python
>
> ```python Python theme={null}
> # Take a screenshot
> await page.screenshot(path="login_screenshot.png")
> ```

## Next steps

> [card] [Session Inspector](https://docs.browserbase.com/platform/browser/observability/observability.md)
>
> Learn how to use the Session Inspector to debug test failures

> [card] [Session Metadata](https://docs.browserbase.com/platform/browser/core-features/session-metadata.md)
>
> Organize and query your test sessions effectively

> [card] [Proxies](https://docs.browserbase.com/platform/identity/proxies.md)
>
> Test your application from different geographic locations

> [card] [Screenshots and PDFs](https://docs.browserbase.com/platform/browser/files/screenshots.md)
>
> Capture visual evidence during test execution


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.