How to update worker.js via API?

I was planning to update worker.js using the API and saw instructions and examples on this documentation page: https://developers.cloudflare.com/api/operations/worker-environment-put-script-content.
I’m using PHP curl, and I encountered difficulties when constructing the Request. First, I didn’t understand the exact usage of and body_part in body:


Then, the sample provided by Cloudflare does not have demonstration data embedded in it. I don’t know how to use this sample to implant my own data. My current Worker only has one js file, worker.js.


$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://api.cloudflare.com/client/v4/accounts/account_identifier/workers/services/service_name/environments/environment_name/content",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "PUT",
  CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"<any part name>\"\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"metadata\"\r\n\r\n\r\n-----011000010111000001101001--\r\n\r\n",
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer undefined",
    "CF-WORKER-BODY-PART: ",
    "CF-WORKER-MAIN-MODULE-PART: ",
    "Content-Type: multipart/form-data; boundary=---011000010111000001101001"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

Can you tell me how to insert my own data into this sample?

I also would like to know how could we do this …

I feel that the sample provided by Cloudflare is the same as not provided, and I don’t know why they didn’t insert data placeholders in the sample.

This is using JavaScript and not PHP, but this is the kind of code you’ll need to upload to the worker PUT endpoint:

const form = new FormData();
form.append('metadata', JSON.stringify({
	main_module: 'index.mjs',
	compatibility_date: '2022-03-11',
}));
form.append('@index.js', new File([
	'export default {async fetch(request, env) { return new Response(\'Hello world!\'); }}',
], 'index.mjs', {
	type: 'application/javascript+module',
}));
const response = await fetch(`https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/workers/services/service_name/environments/environment_name/content`, {
	method: 'PUT',
	headers: {
		'Authorization': `Bearer ${WORKER_UPLOAD_TOKEN}`,
	},
	body: form,
});

There’s not a lot of great documentation around this endpoint unfortunately. The upload code within wrangler is likely going to be your best source for this:

After dozens of attempts, I finally succeeded, and the code is as follows:

<?php
$data = file_get_contents("test.js");  
$delimiter = uniqid(); 
$partname = "worker";
$cf_token = "yourtoken";
$body = "--".$delimiter.PHP_EOL."Content-Disposition:form-data; name=\"".$partname."\";".PHP_EOL.PHP_EOL.PHP_EOL.$data.PHP_EOL;
$body .= "--".$delimiter.PHP_EOL."Content-Disposition:form-data; name=\"metadata\"".PHP_EOL.PHP_EOL."{\"body_part\":\"".$partname."\"}".PHP_EOL;
$body .= "--".$delimiter."--".PHP_EOL.PHP_EOL; 
$curl = curl_init();
curl_setopt_array($curl, [
  CURLOPT_URL => "https://api.cloudflare.com/client/v4/accounts/{account_identifier}/workers/services/{service_name}/environments/production/content",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "PUT",
  CURLOPT_POSTFIELDS => $body,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer ".$cf_token,
    "Content-Length:".strlen($body),
    "Content-Type: multipart/form-data; boundary=".$delimiter
  ],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

how do you include your wrangler.toml?

You’ll need to attach metadata to the request as per my example above.

I don’t use wrangler, I write the original worker.js locally and upload it to my server. Then, the server uses PHP to automatically modify the parts that need to be updated every day, and updates them to Cloudflare via API. If you don’t use PHP, you can try cherryjimbo’s method.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.