Integrate moonbase into your platform
What you're building
Your platform deploys a project to moonbase and gets back the mission's live URL, without your users leaving your product. It's two HTTP endpoints:
• POST /api/projects/upload/stream uploads a ZIP and streams the deploy as it happens.
• GET /api/v1/sites/{address}/status reads a mission's state at any time.
If the mission needs secrets, a third sets them: PUT /api/v1/sites/{address}/env (see API Reference, Environment variables endpoint).
The exact contract is the OpenAPI spec at https://app.moonbase.cloud/api/v1/openapi.json, and the API Reference renders it. This guide walks through what to build, in order.
1. Get and keep an API key
Create a key on the API Keys page in moonbase. It starts with mb_live_ and is shown only once. Send it on every request as Authorization: Bearer mb_live_...
Keep it on your server, as a secret (an environment variable or your secret manager). For curl, pass the Authorization header on standard input or use an owner-only header file. Turn off shell tracing before handling the key. Never put it in browser code, a mobile app, a repository or your logs: anyone with the key can deploy to every mission on that account.
A key works for every mission on its account and can't be limited to one. If your users each have their own moonbase account, each of them gives you their own key. Use one key per integration, so you can revoke it on its own. To rotate: create a new key, switch to it, then delete the old one.
A bad key gets a 401: invalid_key (invalid or revoked), key_expired, or auth_required (no Authorization header).
2. Create a mission, then ship new versions
The first deploy creates a mission: send the ZIP without redeployProjectId. You can pick its address with name (3 to 32 lowercase letters, numbers and single hyphens, starting with a letter); otherwise moonbase picks one.
The done event at the end gives you project_id. Store it with your user's project. Every later deploy sends it as redeployProjectId, and moonbase ships a new version of the same mission at the same URL.
If you only know the mission's address, look the ID up first: GET /api/v1/sites/{address}/status returns it as id. Don't create a new mission with the same name instead: you'll get 409 name_taken.
3. Package the project
Put the project's files at the root of the ZIP, or inside one folder. Leave out node_modules, .git and .env files: moonbase installs dependencies and builds the mission itself, and you don't want secrets in an upload.
moonbase decides how to run the mission:
• Static: a ready-to-serve index.html at the root (no build step needed). A ZIP with just one index.html deploys as a static mission.
• Dynamic: a package.json with a Node server (Express or plain Node), or a project that needs building (Vite, Next.js, React). moonbase builds and runs it, and the stream adds build_stage and build_log events while it builds.
The done event's mode field tells you which one moonbase chose. Per-deploy size limits: 250 MB on moonbase free, 250 MB on moonbase plus, 250 MB on moonbase pro, and 250 MB on moonbase max, never more than 1 GB.
4. Read the response
Check the Content-Type first.
• application/json: the deploy was refused before it started. The body is {"error": "<code>", "message": ...}. See step 6 and Error codes below.
• text/event-stream: the deploy is running. The HTTP status is 200 even if the deploy later fails, so read the stream to the end.
The stream is a series of events, each an event: line, a data: line of JSON and a blank line. It always ends with exactly one of:
• done: the mission is live. url is the live URL, project_id the mission ID.
• error: it isn't. friendly.title, friendly.explanation and friendly.nextSteps are written for your users, code is a stable value to branch on, and trace_id is the error ID to quote to support (the app shows it as Error ID).
Show stage events as progress if you like (subdomain.reservation, payload.upload, ssl.provisioning, verification; each started then completed). Ignore events you don't know, so new ones never break your integration.
Example: curl
Deploys mission.zip as a new version of the mission in MOONBASE_MISSION_ID and prints the live URL or the reason it failed. Needs curl and jq. Load MOONBASE_API_KEY from your secret manager or environment before running. The script sends the header to curl on standard input.
#!/bin/sh
# Deploy mission.zip as a new version of the mission in $MOONBASE_MISSION_ID. Needs curl and jq.
API="${MOONBASE_UPLOAD_URL:-https://upload.moonbase.cloud}"
set +x
printf 'Authorization: Bearer %s\n' "$MOONBASE_API_KEY" | \
curl -sN "$API/api/projects/upload/stream" \
--header @- \
-F "[email protected]" \
-F "redeployProjectId=$MOONBASE_MISSION_ID" > deploy.log
if grep -q '^event: done' deploy.log; then
grep -A1 '^event: done' deploy.log | sed -n 's/^data: //p' | jq -r '"Live: " + .url'
elif grep -q '^event: error' deploy.log; then
grep -A1 '^event: error' deploy.log | sed -n 's/^data: //p' | jq -r '"Deploy failed: " + (.friendly.title // .message) + " (error ID " + .trace_id + ")"'
exit 1
elif jq -e .error deploy.log > /dev/null 2>&1; then
# No stream: a JSON error from before the stream opened.
jq -r '"Deploy failed: " + .error + " — " + (.message // "") + (if .retry_after_sec then " (retry in \(.retry_after_sec)s)" else "" end)' deploy.log
exit 1
else
echo "The stream closed before done or error. Check the mission status before uploading again."
exit 1
fiExample: Node
Node 18 or later, no dependencies. Prints progress, then the live URL. Leave out the mission ID to create a new mission.
// Deploy a ZIP to moonbase and print the live URL. Node 18+, no dependencies.
// MOONBASE_API_KEY=mb_live_... node deploy.mjs mission.zip [missionId]
import { readFile } from "node:fs/promises";
const API = process.env.MOONBASE_UPLOAD_URL ?? "https://upload.moonbase.cloud";
export async function deploy(zipPath, missionId) {
const form = new FormData();
form.append("file", new Blob([await readFile(zipPath)], { type: "application/zip" }), "mission.zip");
if (missionId) form.append("redeployProjectId", missionId); // omit to create a new mission
const res = await fetch(`${API}/api/projects/upload/stream`, {
method: "POST",
headers: { Authorization: `Bearer ${process.env.MOONBASE_API_KEY}` },
body: form,
});
// Problems caught before the stream opens come back as a JSON error.
if (!res.headers.get("content-type")?.includes("text/event-stream")) {
const err = await res.json();
const retryAfter = Number(res.headers.get("retry-after") ?? err.retry_after_sec) || null;
throw Object.assign(new Error(`${res.status} ${err.error}: ${err.message ?? ""}`), { code: err.error, retryAfter });
}
// Read the stream: each event is "event: <name>" + "data: <json>" + a blank line.
const decoder = new TextDecoder();
let buffer = "";
for await (const chunk of res.body) {
buffer += decoder.decode(chunk, { stream: true }).replace(/\r\n/g, "\n");
let end;
while ((end = buffer.indexOf("\n\n")) !== -1) {
const frame = buffer.slice(0, end);
buffer = buffer.slice(end + 2);
const event = frame.match(/^event: ?(.*)$/m)?.[1];
const data = frame.split("\n").filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trimStart()).join("\n");
if (!event || !data) continue;
const payload = JSON.parse(data);
if (event === "stage") console.error(`${payload.name}: ${payload.status}`);
if (event === "done") return payload; // payload.url is the live URL, payload.project_id the mission ID
if (event === "error") {
throw Object.assign(new Error(payload.friendly?.title ?? payload.message), {
code: payload.code ?? null,
retryAfter: payload.retry_after_sec ?? null,
traceId: payload.trace_id,
});
}
}
}
throw new Error("The stream closed before done or error. Check the mission status before uploading again.");
}
const [zipPath, missionId] = process.argv.slice(2);
deploy(zipPath, missionId).then(
(done) => console.log(`Live: ${done.url} (mission ID ${done.project_id})`),
(err) => {
console.error(`Deploy failed: ${err.message}${err.retryAfter ? ` — retry in ${err.retryAfter}s` : ""}`);
process.exit(1);
},
);Example: Python
Python 3.8 or later, standard library only. Prints progress, then the live URL. Leave out the mission ID to create a new mission.
# Deploy a ZIP to moonbase and print the live URL. Python 3.8+, standard library only.
# MOONBASE_API_KEY=mb_live_... python3 deploy.py mission.zip [mission_id]
import json, os, sys, urllib.error, urllib.request, uuid
API = os.environ.get("MOONBASE_UPLOAD_URL", "https://upload.moonbase.cloud")
def multipart(fields, zip_path):
boundary = uuid.uuid4().hex
parts = []
for name, value in fields.items():
parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode())
with open(zip_path, "rb") as f:
parts.append(
f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="mission.zip"\r\n'
f"Content-Type: application/zip\r\n\r\n".encode() + f.read() + b"\r\n"
)
parts.append(f"--{boundary}--\r\n".encode())
return b"".join(parts), f"multipart/form-data; boundary={boundary}"
def deploy(zip_path, mission_id=None):
fields = {"redeployProjectId": mission_id} if mission_id else {} # omit to create a new mission
body, content_type = multipart(fields, zip_path)
req = urllib.request.Request(
f"{API}/api/projects/upload/stream",
data=body,
method="POST",
headers={"Authorization": f"Bearer {os.environ['MOONBASE_API_KEY']}", "Content-Type": content_type},
)
try:
res = urllib.request.urlopen(req, timeout=600)
except urllib.error.HTTPError as e: # a JSON error, before the stream opened
err = json.loads(e.read() or b"{}")
retry = e.headers.get("Retry-After") or err.get("retry_after_sec")
raise RuntimeError(f"{e.code} {err.get('error')}: {err.get('message', '')}" + (f" (retry in {retry}s)" if retry else ""))
if "text/event-stream" not in res.headers.get("Content-Type", ""):
raise RuntimeError(f"Unexpected response: {res.read()[:200]!r}")
event, data = None, []
for raw in res: # one line at a time, as the events arrive
line = raw.decode("utf-8").rstrip("\r\n")
if line.startswith("event:"):
event = line[6:].strip()
elif line.startswith("data:"):
data.append(line[5:].lstrip())
elif line == "" and event and data: # a blank line ends the event
payload = json.loads("\n".join(data))
if event == "stage":
print(f"{payload['name']}: {payload['status']}", file=sys.stderr)
elif event == "done":
return payload # payload["url"] is the live URL, payload["project_id"] the mission ID
elif event == "error":
title = (payload.get("friendly") or {}).get("title") or payload.get("message")
code = f"code {payload['code']}, " if payload.get("code") else ""
raise RuntimeError(f"{title} ({code}error ID {payload.get('trace_id')})")
event, data = None, []
raise RuntimeError("The stream closed before done or error. Check the mission status before uploading again.")
if __name__ == "__main__":
try:
done = deploy(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None)
print(f"Live: {done['url']} (mission ID {done['project_id']})")
except RuntimeError as e:
sys.exit(f"Deploy failed: {e}")5. If the connection drops
Don't upload again straight away: the deploy may still be running, and a second upload would be refused with deploy_in_progress or ship the same version twice. Ask the status endpoint instead. Poll every few seconds until deployInProgress is false, then compare currentVersion with the version before you deployed: higher means the new version is live. Note that the reason for a failed build is only in the stream's error event, not in the status.
// After a dropped stream: wait for the build to finish, then see whether the new version went live.
async function waitForMission(address, versionBefore) {
const API = process.env.MOONBASE_API_URL ?? "https://app.moonbase.cloud";
for (;;) {
const res = await fetch(`${API}/api/v1/sites/${address}/status`, {
headers: { Authorization: `Bearer ${process.env.MOONBASE_API_KEY}` },
});
const mission = await res.json();
if (!res.ok) throw new Error(`${res.status} ${mission.error}`);
if (!mission.deployInProgress) {
return { live: mission.currentVersion > versionBefore, url: mission.publicUrl, version: mission.currentVersion };
}
await new Promise((r) => setTimeout(r, 5000));
}
}
console.log(await waitForMission(process.argv[2], Number(process.argv[3] ?? 0)));6. Limits and retries
Retry only what's meant to be retried, and wait as long as moonbase says:
• 429 rate_limited: too many deploys in a short time. Wait retry_after_sec seconds (also the Retry-After header).
• 409 deploy_in_progress: this mission is still building its previous version. Only one build per mission runs at a time. Wait retry_after_sec seconds, then try again. It doesn't count against your rate limit.
• 500 internal, 503 service_draining, scanner_unavailable, scan_incomplete: a problem on moonbase's side. Retry with a growing delay.
Everything else (400, 401, 402, 403, 404 and the other 409s) means something about the request needs to change first, and the same request will fail again. Show your user the message and nextStep instead.
Allow at least 10 minutes for a stream before giving up on it. Limits per account: a few deploys per 5 minutes and up to 100 per hour, one build at a time per mission, plus your plan's mission, storage and per-deploy size limits.
Error codes
Every error code the API returns, its HTTP status, what it means and what to do. Retry automatically only the ones marked safe to retry.
• auth_required (401) — No API key was sent. What to do: Send Authorization: Bearer mb_live_….
• invalid_key (401) — The key is invalid, revoked, or doesn't have the deploy scope. What to do: Create a new deploy key on the API Keys page and use it instead.
• key_expired (401) — The key has expired. What to do: Create a new deploy key and use it instead.
• no_key (401, status endpoint) — No API key was sent. What to do: Send Authorization: Bearer mb_live_….
• not_found (404, status endpoint) — No mission with this address on the key's account. What to do: Check the address, and that the key belongs to the account that owns the mission.
• email_not_verified (403) — The account's email address isn't verified yet. What to do: The account owner verifies their email, then try again.
• identity_required (403) — The account hasn't finished onboarding. What to do: The account owner finishes onboarding in moonbase, then try again.
• terms_reconsent_required (403) — moonbase's Terms of Service changed since the account owner last accepted them. What to do: The account owner signs in and accepts the current terms, then try again.
• upload_token_slug_mismatch (403) — An upload token was used for a different mission than it was issued for. Not used by API-key callers. What to do: Use the API key, not an upload token.
• malware_detected (403) — The malware scanner found something harmful in the upload. What to do: Remove it. If you think it's a false positive, contact support with the trkId.
• invalid_body (400) — The request couldn't be read as multipart form data — usually a network hiccup. What to do: Retry. Check that you send multipart/form-data with a file field.
• no_file (400) — No file field, or it was empty. What to do: Attach the ZIP as the file field.
• not_zip (400) — The file isn't a ZIP (or a single .html file). What to do: Upload a .zip with an index.html or package.json at its root.
• too_large (400) — The upload is over the largest size moonbase accepts. What to do: Leave out node_modules, build output and unused assets. limit gives the cap in bytes.
• too_large_for_now (400) — The upload is over the size we can take for now (an interim ceiling while large-upload support is finished), even if your plan allows more. What to do: Make the ZIP smaller (leave out node_modules, build output and unused media) and try again. limit gives the current ceiling in bytes.
• invalid_name (400) — name breaks the address rules. What to do: Use 3–32 lowercase letters, numbers and single hyphens, starting with a letter. message says which rule.
• invalid_password (400) — The password sent with a new mission's first deploy is too short (below the admin-set minimum) or longer than 128 characters. What to do: Send a longer password (up to 128 characters), or deploy without password.
• password_protection_coming_soon (400) — A password was sent with a new version of an existing mission. Only a new mission's first deploy can carry one. What to do: Deploy without password, then set or change the password in Mission Control.
• password_protection_disabled (403) — moonbase has paused new password protection, so a first deploy with a password was refused. What to do: Try later, or deploy without password.
• consent_invalid_json (400) — The consent field isn't valid JSON. What to do: Fix or leave out consent.
• upload_check_busy (503) — moonbase is busy and couldn't check this upload just now. Nothing was published. What to do: Try again in a minute.
• zip_unsafe (400) — The ZIP failed a safety check (unusual file count, size or paths). What to do: If it's a normal project, contact support with the trkId.
• no_html_or_package_json_found (400) — There's no index.html or package.json anywhere in the upload. What to do: Include an index.html (static) or a package.json (Node). Doesn't count against your rate limit.
• no_html_found (400) — A static upload with no .html files. What to do: Include an .html file. Doesn't count against your rate limit.
• go_not_supported (400) — A Go project. moonbase doesn't run Go yet. What to do: Upload a built frontend if the project has one. Doesn't count against your rate limit.
• python_entrypoint_not_detected (400) — A Python project with no startable web app. moonbase runs Flask/Django/FastAPI apps that expose a standard WSGI/ASGI app object. What to do: Expose a top-level app object (app = Flask(__name__), app = FastAPI(), or a Django wsgi.py). Doesn't count against your rate limit.
• astro_ssr_not_supported (400) — An Astro project in SSR mode. moonbase deploys static Astro output (astro build → dist/) in v1. What to do: Build Astro as a static site (remove the SSR adapter / set output: 'static'). Doesn't count against your rate limit.
• sveltekit_adapter_node_required (400) — A SvelteKit project using an adapter moonbase can't start. v1 runs @sveltejs/adapter-node only. What to do: Switch svelte.config.js to @sveltejs/adapter-node and re-upload. Doesn't count against your rate limit.
• framework_unsupported:<framework> (400) — The framework was recognised but moonbase can't build it yet. What to do: Deploy a static build instead. Doesn't count against your rate limit.
• classification_error (400) — moonbase couldn't work out how to deploy this upload. What to do: Contact support with the trkId.
• hardcoded_secret_detected (400) — The upload contains what looks like an API key or credential. It was stopped so it doesn't go public. What to do: Remove it (use environment variables) and upload again. Doesn't count against your rate limit.
• plan_limit_exceeded (402) — Over a plan limit: per-deploy size, number of missions, or storage. What to do: reason, limit, current and message say which. Free up room or move to a larger plan.
• weight_overage (402) — The upload would take the account past its free storage. What to do: The account owner upgrades, or frees up storage.
• project_not_found (404) — redeployProjectId isn't a mission on this account. What to do: Look the ID up with the status endpoint, or omit it to create a new mission.
• user_not_found (404) — The key's account no longer exists. What to do: Use a key from a current account.
• name_taken (409) — Another mission already uses this address. What to do: Pick another name. To update your own mission at that address, send its redeployProjectId instead.
• name_recently_used (409) — This address belonged to a recently deleted mission and is still on hold. What to do: Pick another name.
• mission_slug_unusable (409) — This mission's current address is too short to deploy to anymore. What to do: Contact support to get it renamed.
• forbidden (403) — Signed in in the browser as someone the mission is shared with, without permission to deploy (Viewer). An API key never gets this: a key only reaches its own account's missions. What to do: Ask the mission's owner or an admin for Editor access.
• deploy_in_progress (409) — This mission is still building its previous version; one build per mission runs at a time. What to do: Wait retry_after_sec seconds (also the Retry-After header), then try again. Nothing was uploaded and it doesn't count against your rate limit. Safe to retry.
• mission_downgrade_locked (409) — Your plan ended, and this project is over the Free plan's limit, so it's locked. It keeps working, but it can't be deployed, rolled back, resumed or renamed, and its password, environment variables and domains can't be changed. You can still pause, export, archive or delete it. Upgrade to unlock it. If you don't, it will be paused and later deleted; we'll email you before it's deleted. downgrade_state is locked or paused. What to do: Upgrading the plan, or deleting missions until the account fits, unlocks it. The same request returns the same refusal until then.
• consent_required (409) — moonbase wants to change something in this project's build and needs the owner's OK first. What to do: The owner opens consent_url and deploys once from the browser to review proposals. After that, API deploys work again. Doesn't count against your rate limit.
• rate_limited (429) — Too many deploys in a short time (per account or per IP). What to do: Wait retry_after_sec seconds (also the Retry-After header), then try again. Safe to retry.
• internal (500) — Something went wrong on moonbase's side. What to do: Retry once. If it keeps happening, contact support with the trkId. Safe to retry.
• deployment_maintenance (503) — New deployments are temporarily paused for maintenance. What to do: Wait and retry later. Do not change database settings or start duplicate deployments. Safe to retry.
• service_draining (503) — moonbase is restarting. What to do: Retry in a few seconds. Safe to retry.
• scanner_unavailable (503) — The malware scanner is briefly unreachable, so the upload was held rather than deployed unscanned. What to do: Retry in a few minutes. Safe to retry.
• scan_incomplete (503) — The malware scan didn't finish. What to do: Retry in a few minutes. Safe to retry.
• scan_too_large (503) — The file is too large for the malware scanner. What to do: Make the upload smaller, or contact support.