Skip to content

Examples

A scheduled Worker that regenerates files and redeploys a Pages project.

import { deployFiles } from "pages-direct-upload";
export default {
async scheduled(event, env) {
const files = {
"index.html": "<h1>Updated</h1>",
"data.json": JSON.stringify({ updatedAt: Date.now() }),
};
const result = await deployFiles(files, {
accountId: env.CF_ACCOUNT_ID,
projectName: "my-site",
apiToken: env.CF_API_TOKEN,
branch: "main",
});
console.log("deployed", result.id, result.url);
},
};

Store the API token as a secret with wrangler secret put CF_API_TOKEN.

files can also be a Map, which is handy when the paths are built in a loop. This example serves generated scripts as plain text instead of the default for .lua.

import { deployFiles } from "pages-direct-upload";
const files = new Map();
files.set("/index.txt", "cdn\n");
for (const script of scripts) {
files.set(`/${script.mode}/${script.id}.lua`, script.body);
}
await deployFiles(files, {
accountId: env.CF_ACCOUNT_ID,
projectName: "my-cdn",
apiToken: env.CF_API_TOKEN,
branch: "main",
contentTypes: { lua: "text/plain" },
});

The package never touches the filesystem, so read the files yourself and pass them in. A Buffer is a Uint8Array, so it can be passed straight through.

import { readdir, readFile } from "node:fs/promises";
import { join, relative } from "node:path";
import { deployFiles } from "pages-direct-upload";
const dir = "dist";
const entries = await readdir(dir, { recursive: true, withFileTypes: true });
const files = {};
for (const entry of entries) {
if (!entry.isFile()) continue;
const full = join(entry.parentPath ?? entry.path, entry.name);
files[relative(dir, full)] = await readFile(full);
}
const result = await deployFiles(files, {
accountId: process.env.CF_ACCOUNT_ID,
projectName: "my-site",
apiToken: process.env.CF_API_TOKEN,
branch: "main",
});
console.log(result.url);

Windows paths with backslashes are converted to forward slashes automatically.

Include _headers and _redirects in the files and they are applied like they would be from a build folder.

await deployFiles(
{
"index.html": "<h1>hello</h1>",
"_headers": "/*\n X-Frame-Options: DENY\n",
"_redirects": "/old /index.html 302\n",
},
options
);

They are sent as special form parts and do not appear as files on the site. They are not counted in fileCount.

const controller = new AbortController();
setTimeout(() => controller.abort(), 60_000);
await deployFiles(files, {
...options,
signal: controller.signal,
onProgress: (done, total) => console.log(`${done}/${total} assets`),
});
import { CloudflareApiError, deployFiles } from "pages-direct-upload";
try {
await deployFiles(files, options);
} catch (error) {
if (error instanceof CloudflareApiError) {
console.error(`${error.label} failed: ${error.status} (code ${error.code})`);
console.error(error.body);
} else {
throw error;
}
}

A 403 from upload token usually means the API token is missing the Cloudflare Pages: Edit permission or is scoped to a different account.

deployFiles returns as soon as the deployment is created. To wait for it to finish, poll the deployment.

async function waitUntilLive(options, id) {
const url = `https://api.cloudflare.com/client/v4/accounts/${options.accountId}/pages/projects/${options.projectName}/deployments/${id}`;
for (let i = 0; i < 30; i++) {
await new Promise((resolve) => setTimeout(resolve, 3000));
const response = await fetch(url, {
headers: { Authorization: `Bearer ${options.apiToken}` },
});
const { result } = await response.json();
const stage = result?.latest_stage;
if (stage?.name === "deploy" && stage?.status === "success") return true;
if (stage?.status === "failure") return false;
}
return false;
}
const result = await deployFiles(files, options);
const live = await waitUntilLive(options, result.id);

A cron-triggered Worker can fire again before the previous deployment finishes. Combine hashManifest to skip deploys where nothing changed with skipIfInFlight to back off if a deployment from the previous run is still processing.

import { deployFiles, buildManifest, hashManifest, DeploymentInFlightError } from "pages-direct-upload";
export default {
async scheduled(event, env) {
const files = await buildSiteFiles(env);
const prepared = buildManifest(files);
const fingerprint = hashManifest(prepared.manifest);
const lastFingerprint = await env.KV.get("last-deploy-hash");
if (fingerprint === lastFingerprint) {
console.log("no changes, skipping deploy");
return;
}
try {
const result = await deployFiles(files, {
accountId: env.CF_ACCOUNT_ID,
projectName: "my-site",
apiToken: env.CF_API_TOKEN,
branch: "main",
skipIfInFlight: true,
});
await env.KV.put("last-deploy-hash", fingerprint);
console.log("deployed", result.id, result.url);
} catch (error) {
if (error instanceof DeploymentInFlightError) {
console.log("previous run is still deploying, skipping this one", error.deploymentId);
return;
}
throw error;
}
},
};

skipIfInFlight is a look-then-act check against Cloudflare’s own deployment list, not an atomic lock, so it narrows the window where two runs overlap rather than closing it completely. For a hard guarantee, hold a lease in a Durable Object or use a compare-and-set row in D1 around the whole scheduled handler.

Browsers cannot call Cloudflare’s API directly because it does not send CORS headers. Run a small proxy that forwards to the API and point baseUrl at it.

await deployFiles(files, {
...options,
baseUrl: "https://my-proxy.example.com/cloudflare",
});

Requests are sent to {baseUrl}/accounts/... and {baseUrl}/pages/assets/..., so the proxy needs to forward everything under that path to https://api.cloudflare.com/client/v4.

Pass your own fetch to test code that calls deployFiles.

const calls = [];
await deployFiles(files, {
...options,
fetch: async (url, init) => {
calls.push({ url: String(url), method: init?.method ?? "GET" });
return new Response(JSON.stringify({ success: true, result: [] }), {
headers: { "content-type": "application/json" },
});
},
});

buildManifest(files) is also exported to see what a deployment would contain without making any requests.