diff --git a/.changeset/khaki-wasps-glow.md b/.changeset/khaki-wasps-glow.md new file mode 100644 index 000000000000..51cd366ac57f --- /dev/null +++ b/.changeset/khaki-wasps-glow.md @@ -0,0 +1,7 @@ +--- +"wrangler": patch +--- + +fix: wait for actual port before opening browser with `--port=0` + +Previously, running `wrangler dev --remote --port=0` and then immediately pressing `b` would open `localhost:0` in your default browser. This change queues up opening the browser until Wrangler knows the port the dev server was started on. diff --git a/packages/wrangler/src/dev/dev.tsx b/packages/wrangler/src/dev/dev.tsx index 0e0a99a56778..c691951e718c 100644 --- a/packages/wrangler/src/dev/dev.tsx +++ b/packages/wrangler/src/dev/dev.tsx @@ -200,6 +200,17 @@ export function DevImplementation(props: DevProps): JSX.Element { let ip: string; let port: number; +// When starting on `port: 0`, we won't know the port to use until `workerd` has started. If the user tries to open the +// browser before we know this, they'll open `localhost:0` which is incorrect. +let portUsable = false; +let portUsablePromiseResolve: () => void; +const portUsablePromise = new Promise( + (resolve) => (portUsablePromiseResolve = resolve) +); +// If the user has pressed `b`, but the port isn't ready yet, prevent any further presses of `b` opening a browser, +// until the port is ready. +let blockBrowserOpen = false; + function InteractiveDevSession(props: DevProps) { const toggles = useHotkeys({ initial: { @@ -219,6 +230,8 @@ function InteractiveDevSession(props: DevProps) { useTunnel(toggles.tunnel); const onReady = (newIp: string, newPort: number, proxyData: ProxyData) => { + portUsable = true; + portUsablePromiseResolve(); ip = newIp; port = newPort; props.onReady?.(newIp, newPort, proxyData); @@ -660,6 +673,13 @@ function useHotkeys(props: { break; // open browser case "b": { + if (port === 0) { + if (!portUsable) logger.info("Waiting for port..."); + if (blockBrowserOpen) return; + blockBrowserOpen = true; + await portUsablePromise; + blockBrowserOpen = false; + } if (ip === "0.0.0.0" || ip === "*") { await openInBrowser(`${localProtocol}://127.0.0.1:${port}`); return;