Introduction
Browser automation has become an essential tool for developers, whether you are testing web applications, scraping data, or automating repetitive tasks. Stagehand is a modern browser automation framework built on the Chrome DevTools Protocol, designed to make these tasks simpler and faster. Unlike some other frameworks that rely on heavy dependencies, Stagehand provides a lightweight interface to control browsers programmatically, enabling you to interact with web pages, fill out forms, capture responses, and even navigate complex workflows.
In this tutorial, you will learn how to get started with Stagehand using TypeScript. By the end of this guide, you will be able to automate a simple form submission on a live web page, capture the results, and see how Stagehand can fit into your development workflow. This tutorial is designed for developers of all experience levels and will take you step by step from setting up your environment to running working code.
Prerequisites
Before you begin, make sure your development environment meets the following requirements. This will ensure you can follow along smoothly and run Stagehand scripts without issues.
Knowledge
- Basic understanding of JavaScript or TypeScript
- Familiarity with Node.js and npm
- Basic understanding of HTML forms
Software
- Node.js version 18 or higher
- npm (comes with Node.js) or yarn
- Code editor such as Visual Studio Code
- Internet connection to interact with live web pages
- Chrome or Chromium installed locally (Stagehand will launch it automatically)
Optional but helpful tools
- TypeScript installed globally:
npm install -g typescript
- ts-node installed for running TypeScript scripts directly:
npm install -D ts-node
- Node version manager (nvm) to manage multiple Node.js versions
Platform notes
- Mac and Linux users: commands should work natively in Terminal
- Windows users: it is recommended to use PowerShell, Git Bash, or Windows Terminal for a smoother experience
With these prerequisites in place, you are ready to set up your project, install Stagehand, and run your first browser automation script.
Setting Up the Project
Follow these steps to create a new Stagehand project and configure it to run TypeScript scripts.
Step 1: Create a new project folder
mkdir stagehand-demo
cd stagehand-demo
Step 2: Initialize a Node.js project
npm init -y
This will create a package.json file with default settings.
Step 3: Install Stagehand
npm install @browserbasehq/stagehand
Step 4: Install TypeScript and ts-node
npm install -D typescript ts-node
Step 5: Create a TypeScript configuration file
npx tsc --init
Then open tsconfig.json and ensure the following settings are updated:
{
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": false,
"allowSyntheticDefaultImports": true,
"skipLibCheck": true,
"types": ["node"]
}
Step 6: Create a source folder
mkdir src
All TypeScript scripts will go inside this folder.
Step 7: Prepare your environment variables (optional)
If you plan to use Stagehand with Browserbase, create a .env file at the root:
# --- REQUIRED STAGEHAND ENVIRONMENT VARIABLES ---
# 1. BROWSERBASE KEYS (For running the browser in the cloud)
# Get these from: https://browserbase.com/
BROWSERBASE_API_KEY="YOUR_BROWSERBASE_API_KEY"
BROWSERBASE_PROJECT_ID="YOUR_BROWSERBASE_PROJECT_ID"
# 2. LLM API KEY (For the AI brains)
# Get this from: https://ai.google.dev/gemini-api/docs/api-key or your OpenAI dashboard
GOOGLE_API_KEY="YOUR_GOOGLE_API_KEY"
Install dotenv if you want to load environment variables in your scripts:
npm install dotenv
At this point, your project is ready. You can now write your first Stagehand script in src/example.ts and run it using the following command.
npx ts-node src/example.ts
Your First Stagehand Script
Now that your project is set up, let’s write a simple script that opens a browser, navigates to a web page, and prints the page title. This example will help you get comfortable with the basics of Stagehand.
Step 1: Create the script file
Inside your src folder, create a file called example.ts:
touch src/example.ts
Step 2: Add the following code to example.ts
// Load environment variables (optional)
import "dotenv/config";
// Import Stagehand
import StagehandPkg from "@browserbasehq/stagehand";
// Create an async function to run the script
async function main() {
// Initialize Stagehand
const stagehand = new StagehandPkg({
env: "LOCAL" // Use "LOCAL" to run the browser on your machine
});
// Start the browser
await stagehand.init();
// Get the first open page
const page = stagehand.context.pages()[0];
// Navigate to a web page
await page.goto("https://example.com");
// Print the page title
const title = await page.title();
console.log("Page title:", title);
// Close the browser
await stagehand.close();
}
// Run the script
main().catch((err) => {
console.error(err);
process.exit(1);
});
Step 3: Run the script
From the terminal in the project root:
npx ts-node src/example.ts
Expected output
- A new browser window should open automatically and navigate to
https://example.com.
- In the terminal, you should see:
Page title: Example Domain
- The browser will then close automatically.
Step 4: Notes for beginners
StagehandPkg is the default export from the Stagehand package.
stagehand.context.pages()[0] gives you the first browser tab.
page.goto(url) navigates the browser to the specified URL.
page.title() retrieves the page title.
- Always call
stagehand.close() at the end to close the browser and clean up resources.
This simple example shows the core flow of a Stagehand script: initialize the browser, interact with pages, and close the browser. From here, you can move on to more advanced tasks, like filling forms, clicking buttons, and scraping data.
Automating a Simple Form
In this section, we will fill out a form on a web page and submit it using Stagehand. This example demonstrates how to interact with input fields, buttons, and capture results from a page.
Step 1: Create a new script file
Inside your src folder, create a file called form-example.ts:
touch src/form-example.ts
Step 2: Add the following code to form-example.ts
import "dotenv/config";
import StagehandPkg from "@browserbasehq/stagehand";
async function main() {
// Initialize Stagehand
const stagehand = new StagehandPkg({
env: "LOCAL"
});
await stagehand.init();
const page = stagehand.context.pages()[0];
// Navigate to the form page
await page.goto("https://httpbin.org/forms/post");
// Values to fill in
const formValues = {
custname: "Abbas Raza",
custtel: "415-555-0123",
custemail: "abbas@example.com"
};
console.log("Form values before submit:", formValues);
// Fill out the form fields
await page.fill("input[name='custname']", formValues.custname);
await page.fill("input[name='custtel']", formValues.custtel);
await page.fill("input[name='custemail']", formValues.custemail);
// Submit the form
await page.click("form button[type='submit']");
// Wait for navigation or response page to load
await page.waitForTimeout(1000); // short pause to ensure submission completes
// Capture page content after submission
const response = await page.content();
console.log("Response after submit (excerpt):", response.substring(0, 400));
await stagehand.close();
console.log("Form submitted successfully!");
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
Step 3: Run the script
npx ts-node src/form-example.ts
Expected behavior
- A browser window opens and navigates to the HTTPBin form page.
- The form fields for customer name, telephone, and email are filled automatically.
- The form is submitted.
- In the terminal, you will see a log of the values before submission and a snippet of the page content after submission.
- The browser will close automatically after the submission completes.
Step 4: Notes for beginners
page.fill(selector, value) types text into the input field matched by selector.
page.click(selector) simulates a click on a button or other clickable element.
page.waitForTimeout(ms) is used here to ensure the page has enough time to process the submission. For more advanced use, Stagehand provides events to detect page navigation or response.
page.content() retrieves the HTML of the current page, which allows you to verify that the submission succeeded.
This example introduces the key building blocks for automating real-world forms: selecting elements, filling inputs, submitting forms, and reading results.
Best Practices
When building browser automation scripts with Stagehand, following best practices ensures your scripts are reliable, maintainable, and easier to share with your team.
Organize your code clearly
- Separate initialization, navigation, form filling, and submission into logical blocks.
- Use functions for repetitive tasks, such as filling multiple forms or logging in.
Use meaningful variable names
- Name variables according to the data they hold. For example,
custName, custEmail, formValues.
- Avoid generic names like
x or data that make the code harder to read.
Add logging
- Print key actions and values to the terminal to verify what your script is doing.
- For example, log form values before submission and results after submission.
- Stagehand logs also provide context such as browser launch, page navigation, and errors.
Handle waits properly
- Avoid hardcoded long pauses whenever possible. Instead, use Stagehand’s events or element detection to know when a page is ready.
- Examples of waits include checking if an element exists or is visible before interacting with it.
- Using proper waits reduces flakiness and makes scripts faster.
Keep credentials and sensitive data secure
- Store API keys, login credentials, or other secrets in
.env files.
- Do not hardcode secrets in your scripts.
- Use Stagehand’s
env option to access environment variables securely.
Keep scripts maintainable
- Avoid writing very long scripts that do too many things at once.
- Break complex flows into multiple scripts or helper functions.
- Comment your code where the logic is not obvious.
Test scripts regularly
- Run scripts frequently to ensure they still work, especially after updates to Stagehand or the websites you automate.
- Automation can break when web pages change, so proactive testing prevents surprises.
Version control and collaboration
- Keep scripts in a Git repository.
- Share
.env.example files without sensitive values for team members to set up their environment.
- Use consistent coding style and formatting across scripts.
Following these best practices will make your Stagehand scripts more robust, understandable, and easier to maintain as you scale your automation.
Debugging and Troubleshooting
Even with best practices, automation scripts can fail due to page changes, slow network responses, or small mistakes in selectors. Understanding how to debug Stagehand scripts is essential for a smooth development experience.
Enable verbose logging
- Use Stagehand’s built-in logging to see what happens at each step.
- Logs include browser launch, page navigation, element interactions, and errors.
- Example:
{ debug: true } in the Stagehand constructor provides more detailed output.
Check element selectors
- Most failures come from incorrect CSS selectors, XPath expressions, or IDs.
- Use browser developer tools (Inspect Element) to verify selectors before using them in your script.
Inspect page state
- Open the browser in visible mode (
env: "LOCAL") to watch your script interact with the page.
- Pausing scripts at certain points or adding
console.log for element properties can help identify issues.
Handle timing issues
- Avoid assuming pages or elements load instantly.
- Use Stagehand’s built-in methods to wait for elements or page events rather than hardcoded timeouts.
- Example:
await page.waitForSelector("#myInput") ensures the element exists before filling it.
Catch and handle errors gracefully
- Wrap key interactions in
try/catch blocks to handle exceptions without crashing the entire script.
- Log meaningful messages when an error occurs to simplify troubleshooting.
Use environment variables wisely
- Errors often occur when API keys or credentials are missing or incorrect.
- Confirm your
.env file is loaded correctly and that variables are accessed via process.env.VARIABLE_NAME.
Test incrementally
- Don’t run the entire script immediately. Test sections of your automation individually.
- Verify navigation, input, and form submission in smaller steps to isolate problems.
Keep browser sessions clean
- Always close Stagehand with
await stagehand.close() to avoid orphaned browser instances.
- This helps prevent resource exhaustion and makes debugging consistent.
By systematically following these debugging practices, you’ll quickly identify issues, make your scripts more reliable, and save hours of trial-and-error frustration.
Conclusion
Stagehand provides a powerful, developer-friendly way to automate browser workflows without heavy dependencies like Playwright. By following this guide, you now know how to set up Stagehand in a TypeScript project, run your first examples, and handle common pitfalls.
We explored basic form automation, how to capture responses, and best practices for writing stable scripts.
With Stagehand, browser automation becomes more accessible and reliable, allowing you to focus on building intelligent automation flows for testing, data collection, or complex web interactions.
The next steps are to experiment with more complex scenarios, capture network responses, and integrate Stagehand into your broader automation pipelines. Mastery comes from iteration and exploring the full range of Stagehand’s API.
By practicing these workflows, you and your team will be equipped to build scalable, maintainable, and high-performing automation scripts. Stagehand can now be a core tool in your developer toolkit for browser automation.