The staging workflow
Make or refresh a staging copy, push it to the live site, and undo the push if you need to.
2 min read Updated
Try a change on a copy of the site first, then put it live: make or refresh the site's staging copy, deploy to it and check it, push it to the live site, and undo the push if the live site doesn't look right.
What you need
-
A token with
sites:read(View sites) andsites:write(Manage sites). - The live site's id: every staging operation names the live site, never its copy.
1. Make the copy, or refresh it
Read the site's staging. Without a copy, make one; with one, refresh it from the live site, so you start from what's live (the copy's files and database are replaced).
curl -X POST "https://api.rabbitflare.com/v1/sites/8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/staging" \
-H "Authorization: Bearer $RABBITFLARE_TOKEN" const res = await fetch("https://api.rabbitflare.com/v1/sites/8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/staging", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.RABBITFLARE_TOKEN}`,
},
});
if (!res.ok) throw new Error(`Rabbitflare API error ${res.status}: ${await res.text()}`);
const { data } = await res.json();
console.log(data); import { Rabbitflare } from "@rabbitflare/api";
const rf = new Rabbitflare({ token: process.env.RABBITFLARE_TOKEN });
const data = await rf.sites.staging.create({ siteId: "8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d" });
console.log(data); <?php
$ch = curl_init('https://api.rabbitflare.com/v1/sites/8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/staging');
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('RABBITFLARE_TOKEN'),
],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($body === false || $status >= 400) {
throw new RuntimeException("Rabbitflare API error $status: $body");
}
print_r(json_decode($body, true)['data']); import os
import requests
response = requests.post(
"https://api.rabbitflare.com/v1/sites/8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/staging",
headers={
"Authorization": "Bearer " + os.environ["RABBITFLARE_TOKEN"],
},
timeout=120,
)
response.raise_for_status()
print(response.json()["data"]) 2. Wait for it
Each staging operation answers 202 with the operation in activeRun. Read the site's staging until activeRun is
null again: the operation is then first in recentRuns, completed or with its lastError.
Or let webhooks tell you: staging.created, staging.refreshed, staging.pushed, staging.push_undone, or staging.failed or staging.needs_attention when it didn't go through.
Then deploy your change to the copy, and check it at its address.
curl "https://api.rabbitflare.com/v1/sites/8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/staging" \
-H "Authorization: Bearer $RABBITFLARE_TOKEN" const res = await fetch("https://api.rabbitflare.com/v1/sites/8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/staging", {
headers: {
Authorization: `Bearer ${process.env.RABBITFLARE_TOKEN}`,
},
});
if (!res.ok) throw new Error(`Rabbitflare API error ${res.status}: ${await res.text()}`);
const { data } = await res.json();
console.log(data); import { Rabbitflare } from "@rabbitflare/api";
const rf = new Rabbitflare({ token: process.env.RABBITFLARE_TOKEN });
const data = await rf.sites.staging.get({ siteId: "8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d" });
console.log(data); <?php
$ch = curl_init('https://api.rabbitflare.com/v1/sites/8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/staging');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('RABBITFLARE_TOKEN'),
],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($body === false || $status >= 400) {
throw new RuntimeException("Rabbitflare API error $status: $body");
}
print_r(json_decode($body, true)['data']); import os
import requests
response = requests.get(
"https://api.rabbitflare.com/v1/sites/8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/staging",
headers={
"Authorization": "Bearer " + os.environ["RABBITFLARE_TOKEN"],
},
timeout=120,
)
response.raise_for_status()
print(response.json()["data"]) 3. See what a push would do
The preview says what stands in the way (blockers), what's worth knowing (warnings), and the
plugins, themes or WordPress versions a push would put back to an older version (downgrades): a push of those fails unless you name them.
curl "https://api.rabbitflare.com/v1/sites/8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/staging/preview?operation=push&scope=everything" \
-H "Authorization: Bearer $RABBITFLARE_TOKEN" const res = await fetch("https://api.rabbitflare.com/v1/sites/8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/staging/preview?operation=push&scope=everything", {
headers: {
Authorization: `Bearer ${process.env.RABBITFLARE_TOKEN}`,
},
});
if (!res.ok) throw new Error(`Rabbitflare API error ${res.status}: ${await res.text()}`);
const { data } = await res.json();
console.log(data); import { Rabbitflare } from "@rabbitflare/api";
const rf = new Rabbitflare({ token: process.env.RABBITFLARE_TOKEN });
const data = await rf.sites.staging.preview({
siteId: "8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d",
operation: "push",
scope: "everything",
});
console.log(data); <?php
$ch = curl_init('https://api.rabbitflare.com/v1/sites/8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/staging/preview?operation=push&scope=everything');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('RABBITFLARE_TOKEN'),
],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($body === false || $status >= 400) {
throw new RuntimeException("Rabbitflare API error $status: $body");
}
print_r(json_decode($body, true)['data']); import os
import requests
response = requests.get(
"https://api.rabbitflare.com/v1/sites/8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/staging/preview",
headers={
"Authorization": "Bearer " + os.environ["RABBITFLARE_TOKEN"],
},
params={
"operation": "push",
"scope": "everything",
},
timeout=120,
)
response.raise_for_status()
print(response.json()["data"]) 4. Push it to the live site
Push the copy's code (scope: "code": WordPress, plugins and themes), its database, or both. A push needs an
Idempotency-Key: a second push would replace the first one's restore point, so a push sent again must get the first answer, not run
again. Make the key from your deploy's own id (a commit's, say), and running the script again for the same deploy pushes once, for
24 hours (see Idempotency).
# Keep this key when you send the same request again (after a timeout, say), so it's only done once.
KEY=$(uuidgen)
curl -X POST "https://api.rabbitflare.com/v1/sites/8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/staging/actions/push" \
-H "Authorization: Bearer $RABBITFLARE_TOKEN" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: $KEY" \
-d '{
"scope": "code"
}' import { randomUUID } from "node:crypto";
// Keep this key when you send the same request again (after a timeout, say), so it's only done once.
const idempotencyKey = randomUUID();
const res = await fetch("https://api.rabbitflare.com/v1/sites/8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/staging/actions/push", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.RABBITFLARE_TOKEN}`,
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey,
},
body: JSON.stringify({
"scope": "code"
}),
});
if (!res.ok) throw new Error(`Rabbitflare API error ${res.status}: ${await res.text()}`);
const { data } = await res.json();
console.log(data); import { Rabbitflare } from "@rabbitflare/api";
const rf = new Rabbitflare({ token: process.env.RABBITFLARE_TOKEN });
// The SDK sends an Idempotency-Key and keeps it when it sends the request again, so it's only done once.
const data = await rf.sites.staging.push({
siteId: "8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d",
scope: "code",
});
console.log(data); <?php
// Keep this key when you send the same request again (after a timeout, say), so it's only done once.
$idempotencyKey = bin2hex(random_bytes(16));
$ch = curl_init('https://api.rabbitflare.com/v1/sites/8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/staging/actions/push');
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('RABBITFLARE_TOKEN'),
'Content-Type: application/json',
'Idempotency-Key: ' . $idempotencyKey,
],
CURLOPT_POSTFIELDS => json_encode([
'scope' => 'code',
]),
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($body === false || $status >= 400) {
throw new RuntimeException("Rabbitflare API error $status: $body");
}
print_r(json_decode($body, true)['data']); import os
import uuid
import requests
# Keep this key when you send the same request again (after a timeout, say), so it's only done once.
idempotency_key = str(uuid.uuid4())
response = requests.post(
"https://api.rabbitflare.com/v1/sites/8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/staging/actions/push",
headers={
"Authorization": "Bearer " + os.environ["RABBITFLARE_TOKEN"],
"Idempotency-Key": idempotency_key,
},
json={
"scope": "code",
},
timeout=120,
)
response.raise_for_status()
print(response.json()["data"]) 5. Undo it, if you need to
A push keeps a restore point of what it replaced. Undo the push with the restore point's runId, from
restorePoints: the live site is put back as it was. An undo keeps a restore point too, so it can be undone in turn.
# Keep this key when you send the same request again (after a timeout, say), so it's only done once.
KEY=$(uuidgen)
curl -X POST "https://api.rabbitflare.com/v1/sites/8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/staging/actions/undo-push" \
-H "Authorization: Bearer $RABBITFLARE_TOKEN" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: $KEY" \
-d '{
"runId": "7f1e2d3c-4b5a-4968-8776-655443322110"
}' import { randomUUID } from "node:crypto";
// Keep this key when you send the same request again (after a timeout, say), so it's only done once.
const idempotencyKey = randomUUID();
const res = await fetch("https://api.rabbitflare.com/v1/sites/8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/staging/actions/undo-push", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.RABBITFLARE_TOKEN}`,
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey,
},
body: JSON.stringify({
"runId": "7f1e2d3c-4b5a-4968-8776-655443322110"
}),
});
if (!res.ok) throw new Error(`Rabbitflare API error ${res.status}: ${await res.text()}`);
const { data } = await res.json();
console.log(data); import { Rabbitflare } from "@rabbitflare/api";
const rf = new Rabbitflare({ token: process.env.RABBITFLARE_TOKEN });
// The SDK sends an Idempotency-Key and keeps it when it sends the request again, so it's only done once.
const data = await rf.sites.staging.undoPush({
siteId: "8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d",
runId: "7f1e2d3c-4b5a-4968-8776-655443322110",
});
console.log(data); <?php
// Keep this key when you send the same request again (after a timeout, say), so it's only done once.
$idempotencyKey = bin2hex(random_bytes(16));
$ch = curl_init('https://api.rabbitflare.com/v1/sites/8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/staging/actions/undo-push');
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('RABBITFLARE_TOKEN'),
'Content-Type: application/json',
'Idempotency-Key: ' . $idempotencyKey,
],
CURLOPT_POSTFIELDS => json_encode([
'runId' => '7f1e2d3c-4b5a-4968-8776-655443322110',
]),
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($body === false || $status >= 400) {
throw new RuntimeException("Rabbitflare API error $status: $body");
}
print_r(json_decode($body, true)['data']); import os
import uuid
import requests
# Keep this key when you send the same request again (after a timeout, say), so it's only done once.
idempotency_key = str(uuid.uuid4())
response = requests.post(
"https://api.rabbitflare.com/v1/sites/8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/staging/actions/undo-push",
headers={
"Authorization": "Bearer " + os.environ["RABBITFLARE_TOKEN"],
"Idempotency-Key": idempotency_key,
},
json={
"runId": "7f1e2d3c-4b5a-4968-8776-655443322110",
},
timeout=120,
)
response.raise_for_status()
print(response.json()["data"]) What can go wrong
| Code | Status | What it means | What to do |
|---|---|---|---|
staging_busy | 409 | A staging operation is running on this site, or on a site of this server. | Wait until it finishes (activeRun in GET /sites/{siteId}/staging is null again), or cancel it, then try again. |
busy | 409 | Another change is still in progress on this server or site, or something else under way stops this one for now (a site backup running on the server, the server's backups being moved): message says what. | Wait until it finishes, then try again. A change to the server or site itself is done when its pendingAction is null again; for anything else, message says how long to wait. |
limit_reached | 403, 409 | A limit is reached: message says which (servers per account, snapshots per server, domains per site, …). | Delete something first, or contact support to raise the limit. |
feature_unavailable | 403 | This product isn't open to the account. | Contact support if you'd like it opened. |
idempotency_key_required | 400 | This operation needs an Idempotency-Key header: it spends money, or doing it twice isn't the same as doing it once. | Send a unique Idempotency-Key (a UUID) with the request. |
idempotency_key_reused | 422 | The Idempotency-Key was already used in the last 24 hours with another operation or another body, or by another token of the account. | Use a new key for a new request. |
clone_busy | 409 | A clone of this site, or of a site on this server, is being made. | Wait until the clone finishes (or cancel it), then try again. |
Any other refusal stops the script, with the API's code and message: fix the cause, and run that step again.
The whole script
The steps in JavaScript (Node.js 18 or later; save it as staging.mjs), each run at its time: node staging.mjs prepare, then
node staging.mjs push with your deploy's id once you've checked the copy, and node staging.mjs undo if you need to. Put the
live site's id in SITE_ID. Each step waits for its operation, up to 60 minutes, and ends with an error when it
didn't go through.
For another way back, back the site up before the push. After the push, clear the site's caches.
// The staging workflow for one site, in three steps, each run at its time:
// node staging.mjs prepare makes the staging copy, or refreshes it from the live site, and waits for it
// node staging.mjs push <deploy-id> pushes the copy's code to the live site, once you've checked the copy
// node staging.mjs undo puts the live site back as it was before the last push
import { createHash, randomUUID } from "node:crypto";
const API = "https://api.rabbitflare.com/v1";
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Sends a request and gives back its data. Over a rate limit (429) it waits as long as Retry-After says, then sends
// the same request again; any other error is thrown with the API's code.
async function rabbitflare(method, path, body, headers = {}) {
for (;;) {
const res = await fetch(API + path, {
method,
headers: {
Authorization: `Bearer ${process.env.RABBITFLARE_TOKEN}`,
...(body ? { "Content-Type": "application/json" } : {}),
...headers,
},
body: body ? JSON.stringify(body) : undefined,
});
if (res.status === 429) {
await sleep((Number(res.headers.get("Retry-After")) || 1) * 1000);
continue;
}
const answer = res.status === 204 ? null : await res.json().catch(() => null);
if (!res.ok) throw Object.assign(new Error(answer?.error?.message ?? `HTTP ${res.status}`), { code: answer?.error?.code });
return answer?.data ?? null;
}
}
const SITE_ID = "8a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d";
const staging = (path = "") => `/sites/${SITE_ID}/staging${path}`;
// Reads the site's staging every 10 seconds until the operation an answer started has finished.
async function finished(answer) {
const runId = answer.activeRun.id;
const deadline = Date.now() + 60 * 60_000;
for (;;) {
const now = await rabbitflare("GET", staging());
const run = now.activeRun?.id === runId ? now.activeRun : now.recentRuns.find((r) => r.id === runId);
if (run?.status === "completed") return now;
if (run && run.status !== "queued" && run.status !== "running") {
throw new Error(`The ${run.operation} didn't complete (${run.status}): ${run.lastError ?? "see the site's activity"}`);
}
if (Date.now() > deadline) throw new Error("The staging operation isn't done after 60 minutes");
await sleep(10_000);
}
}
const [step, deployId = randomUUID()] = process.argv.slice(2);
if (step === "prepare") {
// 1. A fresh copy of the live site: made, or refreshed when the site has one (the copy's files and database are
// replaced by the live site's).
const now = await rabbitflare("GET", staging());
const answer = now.copy ? await rabbitflare("POST", staging("/actions/refresh")) : await rabbitflare("POST", staging());
const ready = await finished(answer);
console.log(`The staging copy is ready at ${ready.copy.url}: deploy to it and check it`);
} else if (step === "push") {
// 2. What pushing the code would do: stop on anything in the way, or on a plugin it would put back to an older version.
const preview = await rabbitflare("GET", staging("/preview?operation=push&scope=code"));
for (const warning of preview.warnings) console.log(`Note: ${warning}`);
if (preview.blockers.length > 0) throw new Error(`Can't push: ${preview.blockers.join(" ")}`);
if (preview.downgrades.length > 0) {
throw new Error(`The push would put back older versions: ${preview.downgrades.map((d) => `${d.title} ${d.stagingVersion}`).join(", ")}`);
}
// 3. Push the code (WordPress, plugins, themes). A push needs an Idempotency-Key: made from the deploy's id, so
// running this again for the same deploy pushes it once.
const key = "push-" + createHash("sha256").update(`${SITE_ID}/${deployId}`).digest("hex");
const answer = await rabbitflare("POST", staging("/actions/push"), { scope: "code" }, { "Idempotency-Key": key });
const done = await finished(answer);
console.log(`Pushed to ${done.live.url}. Undo it until ${done.restorePoints[0]?.expiresAt} with: node staging.mjs undo`);
} else if (step === "undo") {
// 4. Put the live site back from its restore point, kept by the last push. The key is the restore point's: an
// undo sent twice is done once.
const now = await rabbitflare("GET", staging());
const point = now.restorePoints.find((p) => p.status === "available");
if (!point) throw new Error("There's no push to undo");
const answer = await rabbitflare("POST", staging("/actions/undo-push"), { runId: point.runId }, { "Idempotency-Key": `undo-${point.runId}` });
await finished(answer);
console.log("The live site is back as it was before the push");
} else {
throw new Error("Say which step: prepare, push or undo");
} Still have a question?
Our team answers support tickets about the API, and other developers answer in the community.