Code Examples
Dynamic Callback
Demonstrates how an EdgeWorker can wrap a JSON response with a dynamic unique callback function leveraging Response Provider and Stream API for efficient content transformation. The EdgeWorker should be enabled on JSON requests containing a callback query parameter, which can be managed via Property Manager. When such a request comes in, this EdgeWorker removes the callback query parameter, makes a sub-request to fetch the JSON data, and serves it as a stream. The EdgeWorker code adds a prefix with the callback function name captured from the query parameter and a suffix. Both JSON data and transformed data can be cached using standard ““Caching”” behavior in Property Manager if caching is allowed.
EdgeKV Hello World
The Hello World example demonstrates how you can use EdgeWorkers and EdgeKV to implement a simple Dynamic Content Assembly use case whereby the HTML response is dynamically constructed on the edge based on the content of the Accept-Language header in the client request. It also shows how you could use the getText() helper method.
Find Replace Stream
Demonstrates how an EdgeWorker can modify an HTTP response stream by performing a find & replace operation on the response. The example searches for specific text and replaces it with another across the entire response body. It accepts an optional parameter to specify the number of replacements. If not specified, the replacement occurs as many times as possible. The demo replaces ““This is the original string”” with ““This is the updated string””.
HTML Rewriter
Leverage EdgeWorkers html-rewriter to efficiently generate dynamic HTML content by combining JSON data from an API endpoint with an HTML template. Additionally, if the request is made by a logged-in user, a discount code will be dynamically incorporated into the rendered document. By performing these operations at the Edge with EdgeWorkers, we enhance site performance, offload server resources, and unlock SEO advantages. The template, JSON data, and rendered content can all be efficiently cached at the Edge, further optimizing response times and improving the overall site experience.
Origin Error Handling
Translates a HTTP 503 status code (service unavailable) from an overloaded origin into an HTML page presenting the information in a more user-friendly way. It includes JavaScript to retry after the period indicated by the ‘Retry-After’ header from the origin, if present. Otherwise, it retries after a default number of seconds. Configuring the property to cache HTTP error responses, even for a short duration, makes sense for dynamic content.