Search code examples
javascriptaxiosmultipartform-datacloudflarecloudflare-workers

Cannot upload worker script using Cloudflare API: Main module name is not present in bundle


I'm trying to use this API route of the Cloudflare API to upload a worker with metadata.

I'm using Node.js 18 and Axios 0.29, with the following code:

  const api = axios.create({
      baseURL: 'https://api.cloudflare.com/client/v4',
      headers: {
        Authorization: `Bearer ${myToken}`,
        'Content-Type': 'multipart/form-data',
      },
  })


  const workerCode = `export default {
  async fetch(request, env, ctx) {
    return new Response("Hello World!");
  },
};`

  const form = new FormData();
  form.append('main.js', workerCode);
  form.append(
    'metadata',
    JSON.stringify({
      main_module: 'main.js',
      compatibility_date: '2025-02-04',
      compatibility_flags: ['nodejs_compat'],
    })
  );

  await api.put(
    `/accounts/${accountId}/workers/scripts/${workerName}`,
    form
  );

The error message is always the same: 10021 - Uncaught TypeError: Main module name is not present in bundle

API error

What am I missing? I cannot find any example in the documentation, but I carefully read the API docs and I cannot make it work.

Copy-pasting the worker code manually in the Cloudflare Dashboard works.

Thanks a lot!


Solution

  • On this line:

    form.append('main.js', workerCode);
    

    You are adding the worker code as a string field, but it needs to be a file instead, with a file name.

    Try:

    form.append('main.js', new Blob([workerCode]), 'main.js');
    

    See: https://developer.mozilla.org/en-US/docs/Web/API/FormData/append