Skip to main content
Hyperbrowser allows you to upload files to your browser sessions. This is useful for a variety of use cases, such as:
  • Uploading a CSV file to a website to be used in a form
  • Uploading a PDF file to a website to be used in a form
  • Uploading a Word document to a website to be used in a form
You can upload files to your remote browser session via the Session Uploads API. The name of the file that is uploaded is what it will be saved as in the remote browser session and be stored in the /tmp/uploads directory.
Self-Hosted Hyperbrowser: For some instances of self-hosted Hyperbrowser, uploads will be available at /tmp/<sessionId>/uploads on the host machine.
import { Hyperbrowser } from "@hyperbrowser/sdk";
import { chromium } from "playwright-core";
import { config } from "dotenv";
// import fs from "fs";

config();

const hbClient = new Hyperbrowser({
  apiKey: process.env.HYPERBROWSER_API_KEY,
});

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

const main = async () => {
  const session = await hbClient.sessions.create();
  const liveUrl = session.liveUrl;
  console.log("Live URL:", liveUrl);

  const fileName = "FILENAME.EXTENSION";

  try {
    const result = await hbClient.sessions.uploadFile(session.id, {
      fileInput: fileName,
    });

    // or
    // const fileStream = fs.createReadStream(fileName);
    // const result = await hbClient.sessions.uploadFile(session.id, {
    //   fileInput: fileStream,
    // });

    console.log("Upload success:", result);

    const browser = await chromium.connectOverCDP(session.wsEndpoint);
    const context = browser.contexts()[0];
    const page = context.pages()[0];

    await page.goto("https://browser-tests-alpha.vercel.app/api/upload-test");

    const cdp = await context.newCDPSession(page);
    const root = await cdp.send("DOM.getDocument");

    const inputNode = await cdp.send("DOM.querySelector", {
      nodeId: root["root"]["nodeId"],
      selector: "#fileUpload",
    });
    const remoteFilePath = result.filePath;
    if (!remoteFilePath) {
      console.error("Remote file path not found");
      return;
    }

    await cdp.send("DOM.setFileInputFiles", {
      files: [remoteFilePath],
      nodeId: inputNode["nodeId"],
    });

    await sleep(20_000);
  } catch (err) {
    console.error("Error uploading file:", err);
  } finally {
    await hbClient.sessions.stop(session.id);
  }
};

main().catch((err) => {
  console.error(err);
  process.exit(1);
});