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
- pnpm
- yarn
Add environment variables
Next, let’s add the environment variables to a.env file.
Write a server action
Next, let’s define ourmain function as a server action in app/stagehand/main.ts. This file will have the following three functions:
main: Run the main Stagehand scriptrunStagehand: Initialize and run themainfunctionstartBBSSession: Start a Browserbase session
app/stagehand/main.ts
Create a client component
Next, let’s create a client component that will start a Browserbase session and run themain 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 the StagehandEmbed component
Now, we can use the StagehandEmbed component in our app.
app/page.tsx
Run the app
To run the app, you can use the following command:- npm
- pnpm
- yarn
Deploy the app
To deploy the app, you can use the following commands. First, install the Vercel CLI:- npm
- pnpm
- yarn

