Puppeteer websocket browser CDP: Connect over wss
Puppeteer websocket browser CDP setup: install puppeteer-core, pass the wss URL as browserWSEndpoint, and set defaultViewport to null. Learn auth and retries.
- puppeteer
- cdp
- websocket
- remote browser
- puppeteer-core
On this page
- What is a CDP WebSocket endpoint and how does Puppeteer use it?
- Local Chrome, tunnel, hosted CDP or anti-detect Chromium: which do you need?
- How do you open a Puppeteer WebSocket browser CDP connection over wss?
- How should you authenticate a CDP WebSocket URL?
- How do you handle disconnects and close codes in a Puppeteer WebSocket browser CDP session?
- What happens to cookies, storage and the exit IP between runs?
- How the exit changes IP consistency
- Save and restore cookies in your own code
- How do you intercept requests on a remote browser with the Fetch domain?
- Frequently asked questions
- How do I connect Puppeteer to a browser over a WebSocket CDP endpoint?
- Should I use browser.disconnect() or browser.close() with a hosted browser?
- Can I pass an Authorization header to puppeteer.connect()?
- Does a hosted browser keep my cookies after I disconnect?
- Why does my remote CDP connection time out on the first try?
- What to do next with your Puppeteer WebSocket browser CDP setup
- Sources
For a puppeteer websocket browser cdp connection, install puppeteer-core (no bundled Chrome, per Cloudflare’s Puppeteer guide) and call puppeteer.connect({ browserWSEndpoint: 'wss://...', defaultViewport: null }), the form shown in remote-browser.dev’s connect guide. Setting defaultViewport: null stops Puppeteer from imposing its own viewport on the remote window. Finish with browser.disconnect() to detach from a hosted browser; browser.close() ends the browser itself.
A Puppeteer script that works against a local Chrome changes shape when the browser lives somewhere else. The ws:// URL becomes wss://, a token rides along, the first connection waits through a cold start, and there’s no profile directory to hold your cookies.
In a remote setup your code operates the browser and nobody watches a window. You need to connect, authenticate, handle refused or dropped sockets, and keep state in your own storage between runs.
Key Takeaways
- Chrome 136 ignores
--remote-debugging-porton the default profile, so a local launch needs--user-data-dir.- Close codes 4000-4999 are reserved for private use, so a refusal such as 4007 is an application signal.
What is a CDP WebSocket endpoint and how does Puppeteer use it?
A CDP WebSocket endpoint is a ws or wss URL for the Chrome DevTools Protocol. A Chrome-based browser exposes it, or a host in front of one does. Puppeteer opens that socket, sends JSON commands and receives events. The browser-level endpoint controls every target, and a page-level endpoint controls one tab.

As remote-browser.dev’s CDP guide puts it, Chrome exposes CDP over a WebSocket endpoint, and Puppeteer attaches to it instead of launching a local binary. A command is a JSON message with an id, a method and params. The browser replies with the same id and pushes events on the same socket.
The Target domain splits browser from page. A target is a tab, a worker or the browser itself.
A browser-level URL, with a path starting /devtools/browser/, reaches all of them. A page-level URL, with a path starting /devtools/page/, reaches one.
With browserWSEndpoint, Puppeteer connects at browser level, lists the page targets and wraps each in a Page object. For a remote-only connection, install puppeteer-core, which Cloudflare’s Puppeteer guide describes as “the version without bundled Chrome”.
To try the flow locally, start Chrome with a debugging port and its own profile directory, then ask it for the endpoint:
chrome --remote-debugging-port=9222 --user-data-dir=/tmp/chrome-debug
curl http://127.0.0.1:9222/json/version Read webSocketDebuggerUrl from the JSON response and pass it as browserWSEndpoint.
The second flag isn’t optional. The Chrome for Developers post on Chrome 136 says the debugging switches “will no longer be respected if they point at the default Chrome data directory”, so without --user-data-dir the port never opens.
Local Chrome, tunnel, hosted CDP or anti-detect Chromium: which do you need?
The right option depends on two questions: who operates the browser, and who maintains the machine under it.
| Option | Who runs the browser | Authentication | Session start | State between runs | Exit IP | Fits when |
|---|---|---|---|---|---|---|
| Local debugging port | You | None, localhost only | You launch Chrome | Your user data dir | Your network | A person debugs a script |
| Self-run Chrome behind a tunnel | You | Whatever you put in front | You start the process | Whatever dir you keep | Your server’s network | You own the ops |
| Generic hosted CDP endpoint | Provider | Token | Provider-defined | Provider-defined | Provider-defined | Code needs a browser, no ops |
| Hosted anti-detect Chromium | Provider | Token | Socket open | Saved in your code | Chosen per connection | Code needs a browser identity and exit control |
A person debugging a script wants a window and a local port. Code running in CI or a queue wants a socket it can open and drop.
A tunnel exposes the debugging port to whoever can reach its URL, so you must put authentication and an allow-list in front of it. A hosted endpoint moves that duty to the provider; our roundup of Browserless alternatives compares the generic hosted options.
Playwright users have a parallel route. The Playwright docs state that connectOverCDP() is “significantly lower fidelity than the Playwright protocol connection via browserType.connect()”, and that CDP connections only work with Chromium-based browsers.
Wayfern’s comparison with Multilogin lists its limits plainly: “Wayfern has no customer-facing persistent profiles at all. No named profiles, no cookie import or export, no per-vector fingerprint switches.” You save and restore cookies in your own code.
The same page gives the recommendation: “If hand-managing identities is the job, Multilogin is doing that job and Wayfern is not.” Desktop profile managers suit a person driving many long-lived profiles. A programmable hosted browser suits code.
How do you open a Puppeteer WebSocket browser CDP connection over wss?
To connect Puppeteer to a browser over wss, install puppeteer-core and pass the socket URL to puppeteer.connect() as browserWSEndpoint. This script runs against Wayfern’s hosted anti-detect Chromium:
import puppeteer from 'puppeteer-core';
const url = `wss://api.wayfern.com/ws?token=${process.env.WF_TOKEN}&width=1440&height=900`;
const browser = await puppeteer.connect({
browserWSEndpoint: url,
defaultViewport: null,
});
try {
const page = await browser.defaultBrowserContext().newPage();
await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
console.log(await page.title());
} finally {
await browser.disconnect();
} Install
puppeteer-core. Cloudflare’s Puppeteer guide describes it as “the version without bundled Chrome”, which is what you want when the browser runs elsewhere. Runnpm i puppeteer-core.Build the URL and let the socket open the session. The first message is a JSON “connected” message with
connectionId, then plain CDP. A retry loop that reconnects starts a new session each time.Set
defaultViewport: null. Puppeteer’s connect options saydefaultViewport“Sets the viewport for each page.” and the default is 800x600, which would override the size you asked for. Wayfern’s API reference says it takeswidthandheighton the URL and resizes the real window, so layout andscreen.*values stay consistent.Open the page from the default context.
browser.defaultBrowserContext().newPage()puts the tab where the session’s cookies and storage live. A context you create yourself starts empty, so cookies set in one context aren’t visible in the other.Call
disconnect()infinally. Puppeteer documentsBrowser.disconnect()as disconnecting Puppeteer “from this browser, but leaves the process running”, whileclose()closes the browser and its pages. Over a hosted socket,disconnect()drops your connection and lets the host tear the session down when the last connection closes.
Success looks like the page title printed to your terminal and the process exiting. If the first run hangs, give it time, because the cold start comes before the first page.
Browser time is billed per open-page hour (see the pricing page for the current rate), so a script that crashes before finally and leaves a socket open keeps costing credits. Run the connect script against your own link token and watch the session end when it exits.
How should you authenticate a CDP WebSocket URL?
A CDP WebSocket URL is a bearer credential: anyone who holds the string can drive the browser, so keep it out of places that get copied or logged.
RFC 9110 says that “URIs are intended to be shared, not secured, even when they identify secure resources.” A token in the query string rides in the request line, which a proxy, a load balancer and your application server can each write to an access log. A header stays out of that line.
Puppeteer’s connect() takes a headers option, which pptr.dev’s ConnectOptions page describes as “Headers to use for the web socket connection.” Use it when your provider accepts a header:
const browser = await puppeteer.connect({
browserWSEndpoint: 'wss://provider.example/ws',
headers: { Authorization: `Bearer ${process.env.CDP_TOKEN}` },
defaultViewport: null,
}); Wayfern’s documented form is the token query parameter on /ws, as its API reference shows. Check what any other provider accepts before you pick a form. Where the token must sit in the URL, it helps to know how it’s handled:
- Tokens are shown once and stored hashed, so a lost token has to be replaced with a new one.
Proxy credentials never go in the URL. The own-proxy password is encrypted at rest.
On your side, four habits limit exposure:
- Keep the token in an environment variable.
- Redact query strings in your own logs.
- Mint one token per job or environment, and set an expiry.
- Revoke the token the moment it leaks.
How do you handle disconnects and close codes in a Puppeteer WebSocket browser CDP session?
You handle cold starts, disconnects and close codes by setting timeouts above the cold start, treating every reconnect as a new session, and stopping on refusal codes. Wayfern’s API reference lists the connection parameters.
Set timeouts above the cold start. Set
protocolTimeoutto 90000 ms and wrappuppeteer.connect()in your own 90-second timer. Default timeouts are far shorter, and they’ll fail a healthy first connection.Retry by opening a new socket. Opening the socket starts the session, and there’s no create-session call. A retry is therefore a new session and a new cold start, so cap attempts at two or three.
Listen for the typed disconnect event. Use
BrowserEvent.Disconnectedinstead of the bare string'disconnected'. In the handler, reconnect and restore the cookies you saved yourself.
import puppeteer, { BrowserEvent } from 'puppeteer-core';
const url = `wss://api.wayfern.com/ws?token=${process.env.WF_TOKEN}`;
const timer = new Promise((_, rej) =>
setTimeout(() => rej(new Error('connect timeout')), 90_000));
const browser = await Promise.race([
puppeteer.connect({
browserWSEndpoint: url,
defaultViewport: null,
protocolTimeout: 90_000,
}),
timer,
]);
browser.on(BrowserEvent.Disconnected, () => { /* reconnect, restore state */ }); - Read the close code before retrying. RFC 6455 says “Status codes in the range 4000-4999 are reserved for private use,” so a provider defines those codes itself. If your Puppeteer version doesn’t expose the code, open the URL once with the
wspackage, whosecloseevent passes(code, reason).
Wayfern refuses some requests on purpose. Its anti-detect sessions page says an unknown residential location is refused with close code 4007 instead of falling back to another place. At a zero credit balance, calls are refused and open sessions closed, according to the pricing page.
A retry loop on 4007 repeats the same refusal, so fix the parameter or add credits first.
For example, a request with country=US&city= and a city name missing from the live catalog closes with 4007. You never get a browser in a nearby city, and the same URL produces the same refusal, so your handler should log the code and stop.
What happens to cookies, storage and the exit IP between runs?
Cookies and local storage in a Wayfern session live only while the socket is open, and the exit IP is part of that same state.
A reconnect after the last client left starts from an empty browser, so the cookie jar has to live in your own code.
How the exit changes IP consistency
- Datacenter exit: the default, and egress is free. Every run gets a datacenter address, so nothing ties one run to the next.
- Sticky session: a
sessionid holds one residential IP for a flow. Reuse the id and you keep the address. - Own-proxy traffic is not metered as residential bandwidth.
Wayfern’s use-case page notes that “A cookie issued to one IP and replayed from another is an easy signal for a site to read.” Pair a restored cookie jar with the same sticky session or the same own proxy.
Save and restore cookies in your own code
import fs from 'node:fs/promises';
import puppeteer from 'puppeteer-core';
const url = `wss://api.wayfern.com/ws?token=${process.env.LINK_TOKEN}&country=US&session=run42`;
const browser = await puppeteer.connect({ browserWSEndpoint: url, defaultViewport: null });
const page = await browser.newPage();
const saved = await fs.readFile('cookies.json', 'utf8').catch(() => '[]');
await page.setCookie(...JSON.parse(saved));
await page.goto('https://example.com/account');
// ...do the work...
await fs.writeFile('cookies.json', JSON.stringify(await page.cookies()));
await browser.disconnect(); The same pattern works for localStorage: read it with page.evaluate() before you disconnect and write it back after the next navigation.
How do you intercept requests on a remote browser with the Fetch domain?
You intercept requests on a remote browser by opening a CDPSession on the page, enabling the Fetch domain, and answering every Fetch.requestPaused event.
The Fetch domain’s core commands are Fetch.enable, Fetch.requestPaused, Fetch.continueRequest and Fetch.fulfillRequest.
const client = await page.createCDPSession();
await client.send('Fetch.enable', { patterns: [{ urlPattern: '*' }] });
client.on('Fetch.requestPaused', async ({ requestId, request }) => {
if (request.url.includes('/ads/')) {
await client.send('Fetch.failRequest', { requestId, errorReason: 'BlockedByClient' });
} else {
await client.send('Fetch.continueRequest', { requestId });
}
});
await page.goto('https://example.com'); Every paused request needs one answer: continueRequest, failRequest or fulfillRequest. If a handler skips one, that request never completes and the page stalls. To rewrite a response, call Fetch.fulfillRequest with responseCode and a base64 body.
These are ordinary CDP commands, so they run over the remote socket the same way they run locally. If you don’t need raw CDP, Puppeteer’s page.setRequestInterception(true) with request.abort() and request.continue() is simpler.
Frequently asked questions
How do I connect Puppeteer to a browser over a WebSocket CDP endpoint?
Install puppeteer-core (see Cloudflare’s Puppeteer guide), then call puppeteer.connect({ browserWSEndpoint: 'wss://...', defaultViewport: null }). Keep defaultViewport: null so the remote window size stays as set. Call browser.disconnect() when you finish so your script detaches without closing the remote browser.
Should I use browser.disconnect() or browser.close() with a hosted browser?
Use browser.disconnect() to detach your script.
Can I pass an Authorization header to puppeteer.connect()?
Puppeteer’s connect options include a headers field. Wayfern documents the token as a query parameter, wss://api.wayfern.com/ws?token=LINK_TOKEN, so use that form and keep the URL out of logs.
Does a hosted browser keep my cookies after I disconnect?
No, not after the last connection closes. Read cookies with page.cookies() before you disconnect and restore them with page.setCookie() on the next run.
Why does my remote CDP connection time out on the first try?
Raise protocolTimeout and your connect timer well above the defaults. Retry only on timeouts, not on refusal close codes.
What to do next with your Puppeteer WebSocket browser CDP setup
Today, install puppeteer-core and run the connect example with a link token from your own project, keeping defaultViewport: null so the remote window size stays as you set it.
This week:
- Add a
disconnectedhandler. - Set a timeout above the cold start.
- Stop on close code 4007 instead of retrying.
- Save cookies before you disconnect and restore them on the next run.
Before production:
- Set token expiry and a connection cap.
- Redact the token URL in logs.
- Check the open-page-hour rate on the Wayfern pricing page.
When code is the operator, connect Puppeteer to Wayfern’s hosted anti-detect Chromium over wss and start with the session guide.
Sources
Using with Puppeteer (CDP) · Cloudflare Browser Run docs · Puppeteer Connect to Existing Browser: CDP Guide for… · Changes to remote debugging switches to improve security |… · Wayfern vs Multilogin: anti-detect browser comparison · ConnectOptions | Puppeteer · API Reference - CDP, Web Data & Search | Wayfern · Pricing - Credits for Browsers & the Web Data API | Wayfern · Anti-Detect Browser Sessions over CDP | Wayfern. Every other source is linked where the article cites it.
See us more often in Google
One click marks Wayfern as a preferred source in Google, so our posts can show up more often in your Top Stories, AI Mode and AI Overviews.