Browser Automation

BrowserBase Stagehand: 5-Step Setup Guide for 2025

Get started with BrowserBase Stagehand in 2025. Our simple 5-step guide shows you how to set up your API key, write your first script, and automate browsers.

D

Daniel Carter

A full-stack developer and automation enthusiast simplifying complex web technologies for everyone.

7 min read16 views

Tired of brittle web scrapers that break with the slightest UI change? Or maybe you're bogged down by the complexity of managing headless browsers at scale. If you're nodding along, you're in the right place. BrowserBase Stagehand is here to change the game, offering powerful, reliable browser automation without the usual headaches.

Think of it as a headless browser with a human touch. It handles all the tricky infrastructure—like proxies, CAPTCHA solving, and browser fingerprinting—so you can focus on what matters: getting the data and interactions you need. This guide will walk you through a simple, 5-step process to get you up and running with BrowserBase Stagehand in 2025. Let's dive in!

What is BrowserBase Stagehand?

Before we jump into the setup, let's quickly clarify what Stagehand is. It's the core execution engine of BrowserBase. Instead of writing complex scripts that control a browser step-by-step (like "click here, wait for selector, type this"), you write a single, self-contained function that executes inside the browser context on BrowserBase's secure cloud infrastructure.

This approach has several advantages:

  • Simplicity: You write standard browser-side JavaScript (the kind you'd use in a browser's developer console) to interact with the page. No need to learn a complex new library API.
  • Reliability: BrowserBase manages the browser lifecycle, retries, and other flakiness associated with headless automation. Your code is more robust by default.
  • Performance: Your interaction logic runs directly on the same machine as the browser, eliminating the network latency between your server and the headless browser that plagues traditional setups.

In short, Stagehand lets you tell the browser what to do, and BrowserBase handles the how.

Step 1: Sign Up and Get Your API Key

First things first, you need an account and an API key. This key authenticates your requests to the BrowserBase service.

  1. Navigate to the BrowserBase website and sign up for a new account. They have a generous free tier that's perfect for getting started.
  2. Once you've signed up and logged in, you'll land on your dashboard. Look for the "API Keys" section in the navigation menu.
  3. Generate a new API key. Give it a descriptive name like "My First Project" so you can remember what it's for.
  4. Important: Copy this key and store it somewhere safe. For security reasons, BrowserBase will only show you the key once.

The best practice for using API keys is to store them as environment variables rather than hardcoding them in your script. Create a .env file in your project directory or export it directly in your terminal:

export BROWSERBASE_API_KEY="YOUR_API_KEY_HERE"

This keeps your credentials secure and separate from your code.

Step 2: Install the BrowserBase SDK

BrowserBase provides official SDKs for popular languages to make interacting with the API a breeze. We'll use the Node.js SDK for this guide, as it's a common choice for web-related projects.

Advertisement

Open your terminal, navigate to your project folder, and run the following command to install the SDK using npm:

npm install @browserbase/sdk

Or, if you prefer using Yarn:

yarn add @browserbase/sdk

That's it! The SDK is now added to your project's dependencies, and you're ready to start writing code.

Step 3: Write Your First Stagehand Script

Now for the fun part. Let's write a simple script to visit Hacker News and extract its page title. This is the "Hello, World!" of browser automation.

Create a new file named scraper.js and add the following code:

// scraper.js
import BrowserBase from '@browserbase/sdk';

// Initialize the BrowserBase client.
// It automatically looks for the BROWSERBASE_API_KEY environment variable.
const bb = new BrowserBase();

async function getHackerNewsTitle() {
  console.log("Running Stagehand script on BrowserBase...");

  try {
    // The browse method is where the magic happens
    const result = await bb.browse({
      url: "https://news.ycombinator.com",
      
      // The 'stagehand' function runs inside the cloud browser
      stagehand: async () => {
        // You can use any standard browser APIs here
        const title = document.title;
        return title; // Whatever you return here is sent back
      },
    });

    console.log("✅ Success! Page title:", result);
    return result;
  } catch (error) {
    console.error("❌ Automation failed:", error.message);
  }
}

// Run the function
getHackerNewsTitle();

Breaking Down the Code

  • import BrowserBase from '@browserbase/sdk': We import the necessary library.
  • new BrowserBase(): We create a new client instance. By default, it cleverly finds your API key from the BROWSERBASE_API_KEY environment variable we set earlier.
  • bb.browse({...}): This is the primary method you'll use. It takes an options object.
  • url: "...": The target URL you want the cloud browser to load.
  • stagehand: async () => { ... }: This is the heart of the operation. The function you provide here is serialized and executed directly on the loaded page within the cloud browser. Inside this function, document, window, and all other browser-native APIs are available to you.
  • return title;: The value returned from the stagehand function is the value that your bb.browse() call will resolve to. You can return strings, numbers, objects, or arrays.

Step 4: Execute and Debug Your Script

With your script ready, it's time to run it. Make sure you've set your environment variable, then execute the file from your terminal:

node scraper.js

After a few moments, you should see the output in your console:

Running Stagehand script on BrowserBase...
✅ Success! Page title: Hacker News

Congratulations! You've just successfully run your first browser automation task in the cloud.

What If It Fails? The Power of Debugging

Real-world scraping is rarely this simple. Selectors change, elements don't load, and things break. This is where BrowserBase truly shines.

If your script fails (or even if it succeeds), BrowserBase automatically records the entire session. To view it:

  1. Go back to your BrowserBase dashboard.
  2. Navigate to the "Sessions" or "Logs" tab.
  3. You'll see a list of your recent runs. Find the one you just executed.

Here, you'll find a wealth of information, including:

  • A full video replay of the session.
  • Console logs from the browser.
  • Network requests (HAR file).
  • The exact result or error that was returned.

This makes debugging a visual and intuitive process. You're no longer guessing what the headless browser is seeing; you can watch it happen step-by-step.

Step 5: Integrate with Your Application

A standalone script is great, but the real power comes from integrating this capability into your larger applications. For example, you could build an API that scrapes product information on demand or a scheduled job that monitors website changes.

Here’s a quick example of how you might wrap the Stagehand call in an Express.js API endpoint. This endpoint accepts a URL as a query parameter and returns its title.

// server.js
import express from 'express';
import BrowserBase from '@browserbase/sdk';

const app = express();
const port = 3000;
const bb = new BrowserBase();

app.get('/scrape-title', async (req, res) => {
  const { url } = req.query;

  if (!url) {
    return res.status(400).json({ error: 'URL query parameter is required.' });
  }

  try {
    console.log(`Scraping title from: ${url}`);
    const title = await bb.browse({
      url,
      stagehand: async () => document.title,
    });
    res.json({ url, title });
  } catch (error) {
    console.error("Scraping failed:", error.message);
    res.status(500).json({ error: 'Failed to scrape the specified URL.' });
  }
});

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});

Now you can run this server and make requests to http://localhost:3000/scrape-title?url=https://github.com to get the title of any website dynamically.

Conclusion: Where to Go From Here

You've successfully set up your environment, written and executed your first Stagehand script, and even seen how to integrate it into a web service. In just five steps, you've unlocked a powerful, reliable, and scalable way to automate the web.

This is just the beginning. From here, you can explore more complex tasks:

  • Logging into websites.
  • Filling out and submitting forms.
  • Scraping data from multiple pages.
  • Taking screenshots or downloading files.

The core concept remains the same: write simple, browser-native JavaScript in the stagehand function, and let BrowserBase handle the rest. Dive into the official documentation to discover all the advanced features and happy automating!

Tags

You May Also Like