Trying to call an actor using agent-js from Cloudflare Workers

I’m trying to call an actor method from a Cloudflare worker but unable to make it start.

Cloudflare Workers supports a service worker format and ES Modules for the upload format. I’ve tried both but the import doesn’t work. I’ve use dfx generate to generate the declarations that I’m importing.

When trying the service worker format with type set to webpack, my code looks like this:

import { canisterId } from "../../src/declarations/backend";

addEventListener("fetch", (event) => {
  event.respondWith(handleRequest(event.request));
});
/**
 * Respond with hello worker text
 * @param {Request} request
 */
async function handleRequest(request) {
  console.log(canisterId);
  return new Response("Hello worker!", {
    headers: { "content-type": "text/plain" },
  });
}

The error i get is this:

image

When I try the ES modules format, my code looks like this:

import { canisterId } from "../../src/declarations/backend";

export default {
  fetch(request) {
    console.log(canisterId);
    return new Response("Hello, world!", {
      headers: {
        "Content-Type": "text/plain",
      },
    });
  },
};

image

In the above examples, I was trying to import the actors first but to eliminate further, I’m just importing the canister ID string, but as shown above, the imports are making Cloudflare Workers choke.

Anyone manage to call their canister using agent-js from Cloudflare Workers?

1 Like