Cloudflare Docs
Workers
Workers
Visit Workers on GitHub
Set theme to dark (⇧+D)

addEventListener

​​ Background

The addEventListener function defines triggers for a Worker script to execute. There are currently three types of event listeners - "fetch" listeners which are sent a FetchEvent, "scheduled" listeners which are sent a ScheduledEvent and "queue" listeners which are sent QueueEvent.


​​ Syntax

  • addEventListener(type, listener) : void

    • If multiple "fetch" listeners are registered, when one does not call event.respondWith(), the runtime delivers the event to the next registered listener.
    • A "fetch" listener, "scheduled" listener, and "queue" listener can be registered in the same script.
    • A script can have only one "scheduled" listener.

​​ Parameters

  • type string

    • The only types supported are "fetch", "scheduled" and "queue".
  • listener function

    • The function to handle incoming events to the Worker script. The listener is passed a single argument:

    • event FetchEvent or ScheduledEvent or QueueEvent

    • The events dispatched to a Worker. Refer to FetchEvent or ScheduledEvent.


​​ Examples

​​ Fetch Listener


addEventListener('fetch', event => {
event.respondWith(new Response('Hello world'));
});

​​ Scheduled Listener


addEventListener('scheduled', event => {
event.waitUntil(handleScheduled(event));
});

​​ Queue Listener

A Queue listener acts as a consumer for one or more queues.


addEventListener("queue", (event) => {
event.waitUntil(handleMessages(event));
});