Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
browser automation

How to Use Stagehand With MongoDB Atlas for Browser Automation

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Stagehand and MongoDB Atlas solve different problems. Stagehand drives a browser, while your application server uses the MongoDB driver to read and write Atlas data. Connect them through your application—not by giving Stagehand a MongoDB URI. A safe workflow is: Stagehand operates your web app, the app validates the resulting request, and a server-side service persists data in Atlas.

The architecture that works

Stagehand is a browser-automation layer. Atlas is a managed database. There is no special direct Stagehand-to-Atlas connection that replaces your application code. Keep the Atlas connection string, database user and other secrets in the backend environment or a secret manager. Never put them in browser JavaScript, page content, prompts or client-visible configuration.

  1. Stagehand starts a local or hosted browser and opens your application.
  2. Stagehand performs actions such as clicking, typing and extracting page data.
  3. Your application receives the request through its normal route or API.
  4. The backend authenticates and validates the request, then uses the official MongoDB client to access Atlas.
  5. The backend returns a result that Stagehand can observe or verify in the browser.

This separation also limits damage: a browser session can be discarded without exposing database credentials, and Atlas permissions can be scoped to only the collections and operations the application needs.

Choose compatible Stagehand and browser versions first

Stagehand documentation is versioned. The reviewed quickstart is under v2, the API reference documents v3, and the repository’s main README describes newer SDK setup. Do not mix imports, constructor options or lifecycle methods from different generations. Select one language, check its current documentation, and pin the package version in your lockfile before copying commands.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Stagehand can run a browser locally or use Browserbase as a hosted browser environment. Local execution keeps the process in your infrastructure; hosted execution moves browser operations and session management to that service. The available options depend on the exact Stagehand and Browserbase versions. The available material does not establish a neutral cost or performance winner.

Prerequisites

  • A Node.js project for the Stagehand workflow (the official quickstart is TypeScript-oriented).
  • A Stagehand package version and matching browser-provider configuration.
  • An Atlas deployment, a database user with least-privilege permissions, and the deployment connection string.
  • An application server route that performs the database operation.
  • An Atlas network path: an allowed application IP address, or private networking such as VPC/VNet peering or a private endpoint.
  • Outbound firewall rules that permit TCP traffic to ports 27015–27017 for the cluster hostnames or addresses when your network requires explicit egress rules.

Configure MongoDB Atlas for the backend

Create a restricted database user

In Atlas, create a database user for the application rather than using an account with broad administrative privileges. Grant only the database and actions required by the workflow. Use a separate user for development, staging and production where practical.

Allow the server’s network route

Add the backend’s egress IP address to the Atlas project’s IP access list, or configure private connectivity. A hosted browser does not automatically have permission to reach Atlas. If a browser service were to connect directly, its egress route would have to be explicitly allowed and its credentials carefully scoped; the safer default is for your backend to perform all database access.

Build the connection string

Retrieve the deployment connection string from Atlas. Supply the database name and the database user’s authentication details where required. Put the completed value in an environment variable such as MONGODB_URI; do not commit it to source control.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
MONGODB_URI=mongodb+srv://app_user:[email protected]/automation?retryWrites=true&w=majority

The hostname, credentials and options above are illustrative. Use the exact string Atlas provides for your deployment and URL-encode credentials containing reserved characters.

Connect the application to Atlas

Install the official MongoDB driver in the application that owns the route Stagehand will exercise:

npm install mongodb

A small TypeScript module can reuse one connection pool instead of opening a new connection per request:

import { MongoClient } from "mongodb";

const uri = process.env.MONGODB_URI;
if (!uri) throw new Error("MONGODB_URI is required");

const client = new MongoClient(uri);
let connected: Promise<MongoClient> | undefined;

export function getMongoClient() {
  connected ??= client.connect();
  return connected;
}

export async function createJob(input: { name: string; sourceUrl: string }) {
  const db = (await getMongoClient()).db("automation");
  const result = await db.collection("jobs").insertOne({
    name: input.name,
    sourceUrl: input.sourceUrl,
    createdAt: new Date()
  });
  return result.insertedId;
}

Add request validation, authentication and an application-level authorization check before calling createJob. Do not accept an arbitrary collection name or database command from the browser.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set up Stagehand

Use the Stagehand CLI and initialization sequence from the documentation for the version you pinned. Provider credentials belong in environment variables. The exact names and constructor fields differ between the v2 quickstart, v3 API and newer SDK material, so verify them against that version’s guide rather than combining examples.

The lifecycle rule in the v3 API is explicit: Must be called before using any other methods. In other words, initialize the Stagehand instance before invoking page actions such as act, extract or observe.

// Shape shown for explanation; use the constructor options for your pinned version.
const stagehand = new Stagehand({
  // provider and model settings from the matching Stagehand guide
});
await stagehand.init();
const page = stagehand.page;
await page.goto("https://your-app.example.test/new-job");
await page.act("Fill the job name and source URL, then submit the form");
const confirmation = await page.extract("Return the confirmation text");
console.log(confirmation);

For a hosted browser, configure the Browserbase credentials and session settings required by your selected Stagehand release. For local execution, install and expose the browser runtime required by that release. Treat browser-provider secrets separately from MONGODB_URI.

Build the end-to-end workflow

1. Make the application route deterministic

Give the form stable labels or selectors and return a visible success state after the server has written to Atlas. A confirmation element containing the created record’s identifier is easier to verify than timing-based assumptions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

2. Have Stagehand submit normal application traffic

Stagehand should interact with the page as a user would. The browser sends the request to your app; it does not send an Atlas command. Your server validates the payload, performs the write and renders or returns the result.

3. Verify both sides

Use Stagehand’s extraction or observation capability to verify the UI result. For stronger checks, expose a restricted application endpoint that reads the record by an opaque identifier and returns only the fields needed for the test. Never expose the connection string or unrestricted database queries.

4. Make retries safe

Browser automation can retry after a timeout even when the server completed the write. Use an idempotency key, a unique application identifier or an upsert strategy so a repeated submission does not create unintended duplicates.

Local browser versus hosted Browserbase

Concern Local execution Hosted browser
Where the browser runs Your machine, CI runner or server Provider-managed browser infrastructure
Operations You install, patch and observe the runtime You configure sessions and provider credentials according to the selected version
Atlas access Backend network route must be allowed Backend still needs its own allowed route; browser location does not grant database access
Secrets Keep provider and Atlas secrets in your environment or secret store Keep provider credentials separate from backend database credentials
Cost and speed No neutral comparison established here No neutral comparison established here

Choose based on where you want to operate the browser and how your deployment handles sessions, logging and network egress—not on an assumed performance or price advantage.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Version and Atlas CLI cautions

If you use MongoDB’s Atlas CLI getting-started commands, note that atlas deployments commands are deprecated as of Atlas CLI 1.52.0. The guide directs users toward atlas local for local deployments and atlas clusters for cloud clusters. Confirm the current CLI help before scripting these commands.

Stagehand’s v2 quickstart, v3 API reference and newer main-branch README are not interchangeable. Pin dependencies, record the browser-provider configuration beside the code, and upgrade deliberately.

Security checklist

  • Store MONGODB_URI, Stagehand model credentials and Browserbase credentials outside source code.
  • Use a database user limited to the required database and operations.
  • Allow only the backend’s network route in Atlas, or use private networking.
  • Validate and authorize every browser-submitted request on the server.
  • Redact connection strings, cookies, authorization headers and page content from logs.
  • Use separate Atlas users and deployments for test and production data.
  • Destroy browser sessions and close resources when a job finishes or fails.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting

Stagehand fails before opening a page

Check that the package, initialization API and provider variables belong to the same documented version. Ensure init() runs before page methods and that the local browser or hosted provider is available.

Atlas reports an authentication failure

Verify the database username and password, URL-encode reserved password characters, and confirm that the URI points to the intended deployment and database.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Atlas reports a network timeout

Check the Atlas IP access list or private route from the application server, DNS resolution and outbound firewall rules for ports 27015–27017. Changing from a local browser to a hosted browser does not fix a backend route that is not allowed.

The form succeeds but no document appears

Inspect the server logs and response status, confirm the route uses the expected database and collection, and query by the operation’s idempotency key. Make sure the application is not silently swallowing a rejected insert.

A retry creates duplicates

Add a unique key or idempotent upsert and have Stagehand wait for the confirmation element rather than blindly submitting again after a navigation delay.

Secrets appear in browser logs

Move all Atlas work behind the server route, remove sensitive fields from page output, and redact request and exception logs. A browser automation script should know only the test data it needs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Or skip the browser setup

If your actual requirement is producing screenshots of a page rather than testing an Atlas-backed workflow, ScreenshotNeo provides a single HTTP endpoint. It removes cookie banners, newsletter popups and chat widgets before capture; bot checks, blank pages and failed loads are not billed; its MCP server lets AI agents take screenshots; and the free plan includes 1,000 screenshots a month with no card, while paid plans start at $5 for 3,000.

cURL:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' }); const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

See the ScreenshotNeo documentation for capture options and response headers such as X-Page-Verdict and X-Billed. Sign up free for 1,000 screenshots a month with no card.

FAQ

Can Stagehand connect directly to Atlas?

Not as a replacement for an application backend. Use Stagehand for browser control and an official MongoDB client in your server for Atlas access.

Does Browserbase change Atlas permissions?

No. Atlas permissions and network access still apply to the application connection. Browser hosting and database authorization are separate decisions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Is Atlas App Connections the same as a MongoDB driver connection?

No. Atlas App Connections is an OAuth 2.1 delegated-access mechanism for applications acting on behalf of Atlas users. It is distinct from the ordinary driver connection your backend uses for application data.

Frequently Asked Questions

Can Stagehand connect directly to Atlas?

Not as a replacement for an application backend. Use Stagehand for browser control and an official MongoDB client in your server for Atlas access.

Does Browserbase change Atlas permissions?

No. Atlas permissions and network access still apply to the application connection. Browser hosting and database authorization are separate decisions.

Is Atlas App Connections the same as a MongoDB driver connection?

No. Atlas App Connections is an OAuth 2.1 delegated-access mechanism for applications acting on behalf of Atlas users. It is distinct from the ordinary driver connection your backend uses for application data.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.