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

# Use Stagehand in Next.js

> Next.js is a popular framework for developing web-based applications in production. It powers Stagehand apps like [Director](https://director.ai), [Brainrot](https://brainrot.run) and [Open Operator](https://operator.browserbase.com).

export const V3Banner = () => null;

<V3Banner />

<Card title="Check out the Stagehand Next.js Quickstart" icon="github" href="https://github.com/browserbase/stagehand-nextjs-quickstart">
  Clone our [GitHub repo](https://github.com/browserbase/stagehand-nextjs-quickstart) to get started with Stagehand (v2) in Next.js.
</Card>

## Add Stagehand to an existing Next.js project

If you'd like to start from scratch, you can run:

<Tabs>
  <Tab title="npm">
    ```bash theme={null}
    npm create next-app@latest stagehand-nextjs --yes
    cd stagehand-nextjs
    ```
  </Tab>

  <Tab title="pnpm">
    ```bash theme={null}
    pnpm create next-app@latest stagehand-nextjs --yes
    cd stagehand-nextjs
    ```
  </Tab>

  <Tab title="yarn">
    ```bash theme={null}
    yarn create next-app@latest stagehand-nextjs --yes
    cd stagehand-nextjs
    ```
  </Tab>
</Tabs>

If you'd like to add Stagehand to an existing Next.js project, you can do so by installing the dependencies:

<Tabs>
  <Tab title="npm">
    ```bash theme={null}
    npm install @browserbasehq/stagehand @browserbasehq/sdk playwright zod
    ```
  </Tab>

  <Tab title="pnpm">
    ```bash theme={null}
    pnpm add @browserbasehq/stagehand @browserbasehq/sdk playwright zod
    ```
  </Tab>

  <Tab title="yarn">
    ```bash theme={null}
    yarn add @browserbasehq/stagehand @browserbasehq/sdk playwright zod
    ```
  </Tab>
</Tabs>

### Add environment variables

Next, let's add the environment variables to a `.env` file.

```env theme={null}
BROWSERBASE_API_KEY=your-browserbase-api-key
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**

```ts app/stagehand/main.ts theme={null}
// 🤘 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";
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,
    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({});
  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.

```tsx app/components/stagehandEmbed.tsx theme={null}
"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.

```tsx app/page.tsx theme={null}
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:

<Tabs>
  <Tab title="npm">
    ```bash theme={null}
    npm run dev
    ```
  </Tab>

  <Tab title="pnpm">
    ```bash theme={null}
    pnpm dev
    ```
  </Tab>

  <Tab title="yarn">
    ```bash theme={null}
    yarn dev
    ```
  </Tab>
</Tabs>

### Deploy the app

To deploy the app, you can use the following commands. First, install the Vercel CLI:

<Tabs>
  <Tab title="npm">
    ```bash theme={null}
    npm add -g vercel
    ```
  </Tab>

  <Tab title="pnpm">
    ```bash theme={null}
    pnpm add -g vercel
    ```
  </Tab>

  <Tab title="yarn">
    ```bash theme={null}
    yarn add -g vercel
    ```
  </Tab>
</Tabs>

Then, run the following command to deploy the app:

```bash theme={null}
vercel
```

## References

<CardGroup cols={2}>
  <Card title="Deploy Template (v2)" icon="rocket" href="https://vercel.com/templates/ai/stagehand-next-js-quickstart">
    One‑click deploy the Stagehand Next.js template on Vercel (Stagehand v2)
  </Card>

  <Card title="Source Cod (v2)" icon="github" href="https://github.com/browserbase/stagehand-nextjs-quickstart">
    Browse the complete template repository on GitHub (Stagehand v2)
  </Card>
</CardGroup>
