Puppeteer Remote Browser: WebSocket Auth & Sessions
In this article
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(orpuppeteer-coreif you don't need bundled Chromium). - A remote browser instance. This could be:
- A browser you started yourself with
--remote-debugging-port=9222on 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.
- A browser you started yourself with
- Credentials or a token if the remote browser requires authentication (most do).
Step-by-Step
- Start the remote browser with debugging enabled. If you control the remote machine, launch Chrome/Chromium with:
Addchrome --remote-debugging-port=9222 --remote-debugging-address=0.0.0.0--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. - Get the WebSocket endpoint. For your own browser, hit
http://<remote-ip>:9222/json/versionto get thewebSocketDebuggerUrl(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. - 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 inconnect(), so you'll need to use a library likewsto create a WebSocket with headers, then pass that to Puppeteer'stransportoption.
- Query parameter:
- Connect Puppeteer using
puppeteer.connect(). The basic code:
If you need custom headers, create a WebSocket transport:const puppeteer = require('puppeteer'); const browser = await puppeteer.connect({ browserWSEndpoint: 'ws://remote:9222/devtools/browser/<id>?token=abc', defaultViewport: null // keep remote viewport });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 }); - Create or reuse pages. After connecting, you can use
browser.pages()to get existing tabs, orbrowser.newPage()to open a new one. Note thatnewPage()works, but if the remote browser has a session limit, you may need to close unused pages. - 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();thenconst page = await context.newPage();. This gives you a clean session with separate cookies/storage. Close the context when done to free resources. - 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, useawait 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 ofconnect().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-coreinstead ofpuppeteerif 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
netstatorcurlto 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 theOriginheader 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.