How to use event.waitUntil with Workers KV put? (ReferenceError: event is not defined)

I’m trying to perform an asynchronous write to Workers KV using event.waitUntil() to avoid the put operation blocking the content response to the browser and therefore reduce latency

The problem is that I keep getting this error “ReferenceError: event is not defined at u (worker.js:1:4773)” and I don’t know why.

I’m sure there is a really obvious reason why this isn’t working but I can’t figure it out so I would be very grateful if someone could help!

Here are the relevant sections of code, edited for brevity:

addEventListener('fetch', event => {

    // For easier debugging, exception stack traces are returned in body
    // This MUST be removed/disabled in production!
    .catch(e => new Response(templateHeader(HEADERATTRIBUTES)
    + '<h1>Sorry, that page is temporarily unavailable</h1><p>'
    + e.stack + '</p>'
    + templateFooter(), {
      status: 500,
      statusText: "Internal Server Error",
      headers: GLOBALHEADERS }))


async function handleRequest(request) {

          {expirationTtl: 1209600}));

        // Redirect to next step in sequence
        response = new Response(null, {
          status: 303,
          statusText: "See Other",
          headers: GLOBALHEADERS

        // Return response to browser
        return response;


Code results in error: ReferenceError: event is not defined at u (worker.js:1:xxxx)

You are not passing your event to the handleRequest function, so it’s not able to actually access it, therefor you got a error that says it’s not defined.

This can be easily solved by doing something like:

addEventListener('fetch', event => {
async function handleRequest(event) {
        const { request } = event


If you have any more javascript related questions, I recommend checking out StackOverflow, where you can find and ask javascript questions.

1 Like