Skip to content

Commit

Permalink
fix: wait for actual port before opening browser with --port=0 (#5033)
Browse files Browse the repository at this point in the history
* fix: wait for actual port before opening browser with `--port=0`

* fix: don't allow multiple browser opens when waiting for port
  • Loading branch information
mrbbot authored Feb 16, 2024
1 parent 027f971 commit b1ace91
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .changeset/khaki-wasps-glow.md
Original file line number Diff line number Diff line change
@@ -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.
20 changes: 20 additions & 0 deletions packages/wrangler/src/dev/dev.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>(
(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: {
Expand All @@ -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);
Expand Down Expand Up @@ -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;
Expand Down

0 comments on commit b1ace91

Please sign in to comment.