0

Wait for State

by
Published Oct 17, 2025

Wait for a Machine to reach a specific state. Specify the desired state with the state parameter. See the [Machine states table](https://fly.io/docs/machines/working-with-machines/#machine-states) for a list of possible states. The default for this parameter is `started`. This request will block for up to 60 seconds. Set a shorter timeout with the timeout parameter.

Script fly Verified

The script

Submitted by hugo697 Bun
Verified 235 days ago
1
//native
2
type Fly = {
3
  token: string;
4
};
5
/**
6
 * Wait for State
7
 * Wait for a Machine to reach a specific state. Specify the desired state with the state parameter. See the [Machine states table](https://fly.io/docs/machines/working-with-machines/#machine-states) for a list of possible states. The default for this parameter is `started`.
8

9
This request will block for up to 60 seconds. Set a shorter timeout with the timeout parameter.
10

11
 */
12
export async function main(
13
  auth: Fly,
14
  app_name: string,
15
  machine_id: string,
16
  instance_id: string | undefined,
17
  timeout: string | undefined,
18
  state: "started" | "stopped" | "suspended" | "destroyed" | undefined,
19
) {
20
  const url = new URL(
21
    `https://api.machines.dev/v1/apps/${app_name}/machines/${machine_id}/wait`,
22
  );
23
  for (const [k, v] of [
24
    ["instance_id", instance_id],
25
    ["timeout", timeout],
26
    ["state", state],
27
  ]) {
28
    if (v !== undefined && v !== "" && k !== undefined) {
29
      url.searchParams.append(k, v);
30
    }
31
  }
32
  const response = await fetch(url, {
33
    method: "GET",
34
    headers: {
35
      Authorization: "Bearer " + auth.token,
36
    },
37
    body: undefined,
38
  });
39
  if (!response.ok) {
40
    const text = await response.text();
41
    throw new Error(`${response.status} ${text}`);
42
  }
43
  return await response.text();
44
}
45