User Agents

Web browsers and everyday web tech, explained

Run Browser Automation Actors as Real Time APIs

· 4 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Running browser automation actors as real-time APIs allows you to execute automated browser tasks—like form filling, data scraping, or testing—on demand via HTTP requests. This transforms headless browsers into scalable, on-demand services that integrate directly into web applications, backend systems, or CI/CD pipelines. By exposing automation scripts as APIs, you enable asynchronous, stateless interactions with web pages as if they were standard REST endpoints. This guide walks through setting up such a system using reliable, production-grade tools and patterns.

What You'll Need

  • A server or cloud environment (local machine, VPS, or container platform like Docker)
  • Node.js (v16 or higher) installed
  • Puppeteer or Playwright (Node.js libraries for browser automation)
  • Express.js (minimal web framework for creating APIs)
  • Basic knowledge of JavaScript and REST principles
  • Optional: PM2 (for process management), NGINX (for reverse proxy), or a cloud function platform (e.g., Vercel, AWS Lambda with headless Chrome)

Step-by-Step

  1. Set up your project directory: Create a new folder and initialize it with npm init -y. This generates a package.json file to manage dependencies.
  2. Install required packages: Run npm install express puppeteer (or playwright instead of puppeteer). Express handles HTTP routing; Puppeteer controls Chrome/Chromium in headless mode.
  3. Create the main server file: Name it server.js. Import Express and set up a basic server that listens on a port (e.g., 3000).
  4. Define an API endpoint: Use app.post('/scrape') or app.get('/form') to create a route that triggers a browser action. The client sends data via query parameters or JSON body.
  5. Launch a browser instance inside the route: In the route handler, launch Puppeteer with puppeteer.launch({ headless: true }). For production, add flags like --no-sandbox and --disable-setuid-sandbox if running in containers.
  6. Create a new page and navigate: Use browser.newPage() and page.goto(url) to load the target website. Wait for critical elements using page.waitForSelector() to avoid race conditions.
  7. Interact with the page: Use methods like page.type(), page.click(), or page.evaluate() to simulate user actions. Extract data using page.$$eval() or page.content().
  8. Return results as JSON: After completing the task, format the output (e.g., scraped text, screenshot base64, success flag) and send it via res.json().
  9. Close the browser: Always call await browser.close() after sending the response to free resources. Use try...finally to ensure cleanup even if errors occur.
  10. Test locally: Start the server with node server.js and send a POST request using curl or Postman to verify the endpoint returns expected data.
  11. Secure and scale the API: Add rate limiting with express-rate-limit, validate input, and run the service using PM2 to keep it alive. For high concurrency, consider pooling browser instances or switching to a serverless architecture with pre-warmed environments.
  12. Deploy: Push to a cloud platform (e.g., Heroku, Render, or AWS EC2). Ensure the host supports running headless Chrome. Use environment variables for sensitive settings.

Common Mistakes

  • Forgetting to close the browser: This causes memory leaks and crashes under load. Always wrap cleanup in finally blocks.
  • Not handling timeouts: Pages that hang will block the entire API. Set navigation and action timeouts using page.setDefaultTimeout().
  • Hardcoding URLs or selectors: Makes scripts brittle. Accept selectors and URLs via API parameters when possible.
  • Running without sandbox flags in containers: Leads to crashes. Use --no-sandbox only in secure environments.
  • Exposing the API publicly without rate limiting: Makes it vulnerable to abuse. Always limit requests per IP.

Tips

  • Use waitUntil: 'networkidle0' in page.goto() to ensure dynamic content loads fully.
  • Return screenshots or HTML snapshots on error for debugging.
  • Log actions and errors to help trace issues in production.
  • Use environment variables to toggle headless mode (useful for local debugging).
  • Cache frequently accessed pages or responses if they don’t change often.
  • Structure actors as reusable functions that accept parameters, making them modular.

Troubleshooting

If the API fails to start, check Node.js and Puppeteer installation. Missing Chromium binaries are a common issue—install with npm install puppeteer --ignore-scripts and manually download Chromium if needed. If pages time out, increase timeout values or verify network connectivity. For ERR_CONNECTION_REFUSED, ensure the target site is reachable and not blocked by firewall. If the server crashes under load, reduce concurrency or use a process manager like PM2 to restart failed instances. Monitor memory usage; each browser instance consumes significant RAM. In serverless environments, ensure the function duration allows enough time for page interactions.

Frequently Asked Questions

Can I run this on a shared hosting plan?

No. Most shared hosts block spawning browser processes. Use VPS, dedicated servers, or platforms that support headless Chrome.

Is Puppeteer better than Playwright for APIs?

Both work. Playwright supports multiple browsers and has faster execution, but Puppeteer has broader community support. Choose based on your browser needs.

How do I handle login sessions?

Use page.type() to fill credentials and page.waitForNavigation() after login. Store session cookies with page.context().cookies() for reuse, but avoid hardcoding credentials.

Can I scale this to thousands of requests?

Yes, but not with a single instance. Use load balancing, browser pooling, or serverless functions with concurrency limits to scale safely.

Are there security risks?

Yes. Never expose raw DOM access. Validate all input, sanitize URLs, and run the service in isolated environments to prevent code injection or SSRF attacks.