Refactor a Worker to a Pages Function: Problem!

Hi all,

I am new to Cloudflare but find it incredible… So I try to learn fast.

Up to know I managed to have a Worker (worker.js) working fine.

Since It needs to be called from web pages, I have created a Pages app that gets the responses from the server.
But in order to have all in one place. I wish I could get my worker.js within my Pages project.

I tried to tweak it from the worker.js into _worker.js as adviced by Cloudflare (Refactor a Worker to a Pages Function) but got exeptions and the style.json from pages is not even provided anymore.

I am sure it is close but still blocked.

What I have done so far :

  • added to my Pages project folder on my desktop a _worker.js file which is a copy of my worker.js that was working as a Worker.
  • deployed this folder in a new Pages project

=> No luck. Got Exception Error 1101 Worker threw exception.
Looking in logs :
“diagnosticsChannelEvents”: ,
“exceptions”: [
{
“name”: “TypeError”,
“message”: “Cannot read properties of undefined (reading ‘get’)”,

Help would be great !

P.S : my module is in ES modules format.

Are you able to share a git repository with the worker code?

The functionality of the worker will dictate the how it is transformed into pages functions. Does it run on all paths, or only certain paths (e.g. /api/endpoint?)

When using advanced mode, you need to bundle the worker—Cloudflare Pages build system doesn’t handle the bundling (if I recall correctly.)

A simple “hello world” function would look like
Worker

export default {
  async fetch(request, env, ctx) {
    return new Response("Hello World!")
  }
}

Pages Function

export const onRequestGet = async ({ request, env }) => {
    return new Response("Hello World!")
}

With the above examples, it wouldn’t matter if the request to the worker was a GET, POST, HEAD, etc. the worker would always respond with “Hello World!”
However, with the pages function anything other than a GET request will return a 405 Method Not Allowed. This goes back to what I said at the top about the functionality of the worker.