Event handler functions

Understand when EdgeWorker scripts are executed.

The EdgeWorkers code is invoked based on specific HTTP events.
Event Handler Functions
  1. onClientRequest: This event happens for every request as the request is received, before checking if a response is available in cache. Use this event for request modifications before going to cache or to origin. Here’s an example of a function that modifies the response based on user location:
    // redirect based on originating country of request
     
    export function onClientRequest(request) {
       var country = request.userLocation.country;
        if (country === 'FR') {
           request.respondWith(302, {'Location': ['https://www.example.com/fr/']}, '');
        }
    }
    
  2. onOriginRequest: This happens just before sending the request to the origin. This event only happens if the response is not served from cache and not constructed on the edge. Use this event if you want to affect the response coming back from the origin. This function adds a device type header to the origin request:
    // send header to origin
     
    export function onOriginRequest(request) {
       if (request.device.isMobile) { 
          request.setHeader('X-MyHeader-DeviceType','Mobile'); 
       } 
       else if (request.device.isTablet) { 
          request.setHeader('X-MyHeader-DeviceType', 'Tablet'); 
       } 
       else { 
          request.setHeader('X-MyHeader-DeviceType', 'Desktop'); 
       }
    }
    
  3. onOriginResponse: This event happens as the origin response is created. The event only happens if the response is not served from cache and not constructed on the edge. Use this event if you want to modify the response before it is cached.
    // remove header returned from origin
     
    export function onOriginResponse(request, response) {
    response.removeHeader('InternalDebugHeader');
    }
    
  4. onClientResponse: This example shows how to set a header to be sent to the client:
    // add response header
     
    export function onClientResponse(request, response) {
    response.addHeader('Powered-By','Akamai EdgeWorkers');
    }

To create a function for any of these events, implement the callbacks as explained in the JavaScript object reference.