JavaScript Runtime APIs - AddEventListener
How it works
The addEventListener function defines the trigger for the execution of JavaScript code to receive the request data. The event listener type is fetch and gets the fetchEvent
Inside an Azion function, addEventListener is the entry point that wires your code to the request lifecycle. When the runtime receives an incoming HTTP request, it dispatches a fetch event, and the listener you register is the callback that runs to build and return a response. Because the function executes on Azion’s distributed network close to the end user, registering the handler this way lets you intercept, inspect, and respond to traffic with minimal latency. You typically register a single fetch listener per function and call event.respondWith() from within it to deliver the final response.
Syntax
addEventListener(type, listener)Properties
-
type:
string- the supported type isfetch. -
listener:
function- the function that handles incoming Azion Cells events.
Example
addEventListener("fetch", event => { return event.respondWith( new Response("Hello world") ) })Use cases
- Registering the main
fetchhandler that powers an application, routing requests to the right logic based on path or method. - Intercepting incoming requests to add authentication, rewrite headers, or perform redirects before reaching an origin.
- Generating dynamic responses directly on Azion’s global network, such as personalized content or A/B testing variants.
- Implementing custom caching strategies by inspecting the request and returning a synthesized response.
Related resources
For more information on addEventListener visit MDN Web Docs.