User Agents

Web browsers and everyday web tech, explained

Puppeteer Remote Browser: WebSocket Auth & Sessions

· 5 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

Connecting Puppeteer to a remote browser over WebSocket lets you control a browser running on another machine or in the cloud—useful for CI/CD, server-side scraping, or sharing a browser pool. This guide covers the two common scenarios: using a browser already started with --remote-debugging-port (which may require a token) and using a browser automation service that provides a WebSocket endpoint with authentication. You'll learn how to authenticate, manage sessions, and avoid common pitfalls.

What You'll Need

  • Node.js (v14 or later) and npm installed.
  • Puppeteer installed in your project: npm install puppeteer (or puppeteer-core if you don't need bundled Chromium).
  • A remote browser instance. This could be:
    • A browser you started yourself with --remote-debugging-port=9222 on a server (accessible via IP/domain).
    • A browser provided by a third-party service (e.g., Browserless, BrowserStack, or a custom cloud browser) that gives you a WebSocket URL.
  • Credentials or a token if the remote browser requires authentication (most do).

Step-by-Step

  1. Start the remote browser with debugging enabled. If you control the remote machine, launch Chrome/Chromium with:
    chrome --remote-debugging-port=9222 --remote-debugging-address=0.0.0.0
    Add --remote-allow-origins=* if you're connecting from a different origin (common in newer Chrome versions). If you're using a service, skip this—they handle it.
  2. Get the WebSocket endpoint. For your own browser, hit http://<remote-ip>:9222/json/version to get the webSocketDebuggerUrl (e.g., ws://192.168.1.10:9222/devtools/browser/<id>). For third-party services, they usually provide a full WebSocket URL directly in their dashboard or API response.
  3. Handle authentication in the WebSocket URL. If the remote browser requires a token, you can often append it as a query parameter or use a header. Common patterns:
    • Query parameter: ws://host:port/devtools/browser/<id>?token=YOUR_TOKEN
    • Header: Some services require a custom header like Authorization: Bearer YOUR_TOKEN. Puppeteer doesn't support custom headers directly in connect(), so you'll need to use a library like ws to create a WebSocket with headers, then pass that to Puppeteer's transport option.
  4. Connect Puppeteer using puppeteer.connect(). The basic code:
    const puppeteer = require('puppeteer');
    const browser = await puppeteer.connect({
      browserWSEndpoint: 'ws://remote:9222/devtools/browser/<id>?token=abc',
      defaultViewport: null // keep remote viewport
    });
    If you need custom headers, create a WebSocket transport:
    const WebSocket = require('ws');
    const puppeteer = require('puppeteer');
    
    const ws = new WebSocket('ws://remote:9222/devtools/browser/<id>', {
      headers: { 'Authorization': 'Bearer YOUR_TOKEN' }
    });
    
    const browser = await puppeteer.connect({ transport: ws });
  5. Create or reuse pages. After connecting, you can use browser.pages() to get existing tabs, or browser.newPage() to open a new one. Note that newPage() works, but if the remote browser has a session limit, you may need to close unused pages.
  6. Manage sessions. A session in Puppeteer's remote context is the browser itself. To isolate work, create a new incognito browser context: const context = await browser.createBrowserContext(); then const page = await context.newPage();. This gives you a clean session with separate cookies/storage. Close the context when done to free resources.
  7. Disconnect properly. Use await browser.disconnect(); to close the WebSocket without killing the remote browser. This is crucial when you want to keep the browser running for other connections. If you want to shut it down, use await browser.close(); (but that may not be allowed on remote services).

Common Mistakes

  • Forgetting to enable remote debugging on the remote browser. Without --remote-debugging-port, the browser won't expose a WebSocket endpoint.
  • Using puppeteer.launch() instead of connect(). launch() starts a local browser; connect() attaches to an existing one.
  • Ignoring CORS/origin restrictions. Newer Chrome versions block connections from non-matching origins. Add --remote-allow-origins=* or set the correct origin.
  • Hardcoding the WebSocket URL with a token that expires. Many services rotate tokens; always fetch the endpoint dynamically.
  • Not closing browser contexts. Each createBrowserContext() consumes memory; forgetting to close them can crash the remote browser.

Tips

  • Use puppeteer-core instead of puppeteer if you don't need the bundled Chromium—it reduces download size and avoids version mismatches.
  • Set a timeout for connect() (e.g., protocolTimeout: 180000) to avoid hanging when the remote is slow.
  • For production, use environment variables for the WebSocket URL and token, never hardcode them.
  • If you need to run multiple sessions, consider using a pool of remote browsers or a service that supports multiple concurrent connections.
  • Test your connection with a simple script that prints the browser version before building complex logic.

Troubleshooting

  • Connection refused or timeout. Check that the remote browser is running and the port is open (use netstat or curl to test). Ensure the firewall allows the port.
  • 401 Unauthorized or 403 Forbidden. Your token is missing, expired, or not being sent correctly. Verify the token in the URL or header, and check the service's documentation for the exact header name.
  • WebSocket handshake fails with 'Origin' error. Add --remote-allow-origins=* to the remote browser launch flags, or set the Origin header to match what the browser expects.
  • Puppeteer throws 'Target closed' or 'Protocol error'. The remote browser may have crashed or the WebSocket dropped. Reconnect with a fresh endpoint. Also, avoid calling browser.close() if you intend to keep the browser alive.
  • Pages load slowly or hang. The remote browser might be overloaded. Check its resource usage, and consider closing unused pages/contexts.

Frequently Asked Questions

Can I connect to a remote browser without a token?

Yes, if the browser is started without authentication (e.g., on a trusted internal network). Just use the plain WebSocket URL. But this is risky if exposed to the internet.

How do I keep the remote browser running after my script ends?

Use browser.disconnect() instead of browser.close(). This closes the WebSocket but leaves the browser process alive.

Can I use Puppeteer with a remote browser that requires a username/password?

Usually the authentication is token-based, not username/password. If the service uses basic auth, you can include credentials in the URL: ws://user:pass@host:port/..., but this is insecure. Better to use a token header.

What is the difference between puppeteer.connect() and puppeteer.launch()?

launch() starts a new browser locally. connect() attaches to an already-running browser via WebSocket—this is what you use for remote browsers.

How do I handle multiple users on the same remote browser?

Use browser.createBrowserContext() for each user. Each context has isolated cookies and storage, preventing data leaks between sessions.

Why does my remote browser close when I try to use it?

If you call browser.close() in your script, it shuts down the remote browser. Also, some services have idle timeouts—keep the connection active or reconnect as needed.