Trouble Accessing FetchEvent in Hono JS Context on Cloudflare Workers

199 views Asked by At

I'm developing a Cloudflare Workers application using Hono JS and encountering an issue where I'm unable to access FetchEvent within the Hono context. The application works fine with itty router and the default Cloudflare worker setup, but with Hono, I'm facing difficulties.

Here's a snippet of my index.js:

const app = new Hono();

app.get('/backgroundsounds', async (c) => {
    const event = c.event
    console.log("Event is", event);
    return await handleBackgroundSoundsGetAll(c);
});

export default app;

And here is my handleBackgroundSoundsGetAll function:

    export const handleBackgroundSoundsGetAll = async (c) => {
    const { MY_BUCKET } = c.env;

    const request = c.req; // Access the request from the Hono context
    const cacheUrl = new URL(request.url);

    const cacheKey = new Request(cacheUrl.toString(), { method: 'GET' });
    const cache = caches.default;
    const fileName = "backgroundsounds.json";

    console.log("Checking cache for key", cacheKey);
    let response = await cache.match(cacheKey);
    console.log("Cache match result", response);

    // Access R2 bucket from environment bindings
    const backgroundSoundsJson = c.env.MY_BUCKET.get(fileName);
    console.log("Fetching object and ETag from R2 bucket in the background");

    if (response) {
        console.log("Cache hit, serving response");
        if (c.event) {
            c.event.waitUntil(...)
        }
        return response;
    } else {
        // Additional handling for cache miss
    }
};

I'm getting an error saying This context has no FetchEvent. I'm not sure what I'm missing or doing wrong. The same logic works when I use itty router or the standard Cloudflare worker setup.

Has anyone encountered a similar issue with Hono on Cloudflare Workers or can point out what might be going wrong with my implementation?

Any insights or suggestions would be greatly appreciated!

1

There are 1 answers

0
Kian On

You're using Module Workers (export default), rather than Service Workers, so there is no more addEventListener or events.

You will have c.req, c.env and c.executionCtx instead.

c.req is a Request object equivalent to event.request.

c.env contains your bindings, which are no-longer globals but instead on the env object.

c.executionCtx contains waitUntil() and passThroughOnException() which are equivalent to the methods that would have been on the event object.

Take a look at Hono's Cloudflare Workers guide and the Context API reference.