Skip to main content

Check out the Stagehand Next.js Quickstart

Clone our GitHub repo to get started with Stagehand (v2) in Next.js.

Add Stagehand to an existing Next.js project

If you’d like to start from scratch, you can run:
  • npm
  • pnpm
  • yarn
npm create next-app@latest stagehand-nextjs --yes
cd stagehand-nextjs
If you’d like to add Stagehand to an existing Next.js project, you can do so by installing the dependencies:
  • npm
  • pnpm
  • yarn
npm install @browserbasehq/stagehand @browserbasehq/sdk playwright zod

Add environment variables

Next, let’s add the environment variables to a .env file.
BROWSERBASE_API_KEY=your-browserbase-api-key
BROWSERBASE_PROJECT_ID=your-browserbase-project-id
OPENAI_API_KEY=your-openai-api-key

Write a server action

Next, let’s define our main function as a server action in app/stagehand/main.ts. This file will have the following three functions:
  1. main: Run the main Stagehand script
  2. runStagehand: Initialize and run the main function
  3. startBBSSession: Start a Browserbase session
app/stagehand/main.ts
// 🤘 Welcome to Stagehand!
// This file is from the [Stagehand docs](https://docs.stagehand.dev/sections/examples/nextjs).

"use server";

import { Stagehand } from "@browserbasehq/stagehand";
import { z } from "zod/v3";
import { Browserbase } from "@browserbasehq/sdk";

/**
 * Run the main Stagehand script
 */
async function main(stagehand: Stagehand) {
  // You can use the `page` instance to write any Playwright code
  // For more info: https://playwright.dev/docs/pom
  const page = stagehand.context.activePage();

  // In this example, we'll get the title of the Stagehand quickstart page
  await page?.goto("https://docs.stagehand.dev/");
  await stagehand.act("click the quickstart link");
  const { title } = await stagehand.extract(
    "extract the main heading of the page",
    z.object({
      title: z.string(),
    }),
  );

  return title;
}

/**
 * Initialize and run the main() function
 */
export async function runStagehand(sessionId?: string) {
  const stagehand = new Stagehand({
    env: "BROWSERBASE",
    apiKey: process.env.BROWSERBASE_API_KEY,
    projectId: process.env.BROWSERBASE_PROJECT_ID,
    verbose: 1,
    logger: console.log,
    browserbaseSessionID: sessionId,
    disablePino: true,
  });
  await stagehand.init();
  const result = await main(stagehand);
  console.log(result);
  await stagehand.close();
}

/**
 * Start a Browserbase session
 */
export async function startBBSSession() {
  const browserbase = new Browserbase();
  const session = await browserbase.sessions.create({
    projectId: process.env.BROWSERBASE_PROJECT_ID!,
  });
  const debugUrl = await browserbase.sessions.debug(session.id);
  return {
    sessionId: session.id,
    debugUrl: debugUrl.debuggerFullscreenUrl,
  };
}

Create a client component

Next, let’s create a client component that will start a Browserbase session and run the main function with the server actions we just defined. We’ll first create a Browserbase session and embed the session in an iframe before running the main function.
app/components/stagehandEmbed.tsx
"use client";

import { useCallback, useState } from "react";
import { runStagehand, startBBSSession } from "@/app/stagehand/main";

export function StagehandEmbed() {
  const [sessionId, setSessionId] = useState<string | null>(null);
  const [debugUrl, setDebugUrl] = useState<string | null>(null);

  const startSession = useCallback(async () => {
    const { sessionId, debugUrl } = await startBBSSession();
    setSessionId(sessionId);
    setDebugUrl(debugUrl);
    await runStagehand(sessionId);
  }, []);

  return (
    <div>
      {!sessionId && <button onClick={startSession}>Start Session</button>}
      {sessionId && debugUrl && (
        <iframe src={debugUrl} className="w-full h-full" />
      )}
    </div>
  );
}

Use the StagehandEmbed component

Now, we can use the StagehandEmbed component in our app.
app/page.tsx
import { StagehandEmbed } from "@/app/components/stagehandEmbed";

export default function Home() {
	return (
		<main>
			<StagehandEmbed />
		</main>
	)
}

Run the app

To run the app, you can use the following command:
  • npm
  • pnpm
  • yarn
npm run dev

Deploy the app

To deploy the app, you can use the following commands. First, install the Vercel CLI:
  • npm
  • pnpm
  • yarn
npm add -g vercel
Then, run the following command to deploy the app:
vercel

References