JavaScript examples
Copy ready-to-use JavaScript snippets for functions, from returning a response to reading cookies and denying requests on a firewall.
Copy any of these JavaScript snippets into a function as a starting point for your own code. The examples cover the patterns functions are most often used for: returning a response or a JSON payload, redirecting traffic, reading cookies, running an A/B test, and denying a request by country. They are grouped by where the function runs: Applications, for functions that handle the fetch event on an application, and Firewall, for functions that handle the firewall event on a firewall.
Most handlers in this collection are written in the Service Worker pattern, which registers the handler with addEventListener. New code uses ES Modules, and Process a request body is written that way: refer to Best practices for the current pattern, and to Migrate handler patterns in Functions for the before-and-after of each handler.