This guide offers a high-level overview and illustrative examples for migrating from Cloudflare Workers to Edgio Edge Functions. It is designed to help developers familiar with Cloudflare Workers understand the transition to Edge Functions by offering sample code for a general understanding of the migration process.
Function Signature
- Cloudflare Worker:
export default { async fetch(request) { ... } }
- Edgio:
export async function handleHttpRequest(request, context) { ... }
To convert from a Cloudflare Worker to an Edgio Edge function, you need to make the following changes:
- Rename the function from
fetch
tohandleHttpRequest
and export it. - Include both
request
andcontext
as arguments to the function. - Adjust any references to specific Cloudflare Worker properties or methods to their equivalent Edgio counterparts. See Edge Function parameters.
- Return a
Response
orPromise<Response>
instance.
Origin Configuration
In order to fetch content from an origin, you need to specify the origin in
edgio.config.js
and include it in the fetch()
call in the edge function. See origin requests using fetch() for configuration requirements.Examples
Basic HTML Response
The following example shows how to return a basic HTML response with the appropriate
Content-Type
header.Cloudflare Worker Snippet
JavaScript
1export default {2 async fetch(request) {3 const html = `<!DOCTYPE html>4 <body>5 <h1>Hello World</h1>6 <p>This markup was generated by a Cloudflare Worker.</p>7 </body>`;89 return new Response(html, {10 headers: {11 'content-type': 'text/html;charset=UTF-8',12 },13 });14 },15};
Edge Function Equivalent
JavaScript
1export async function handleHttpRequest(request, context) {2 const html = `<!DOCTYPE html>3 <body>4 <h1>Hello World</h1>5 <p>This markup was generated by an Edgio Edge Function.</p>6 </body>`;78 return new Response(html, {9 headers: {10 'Content-Type': 'text/html;charset=UTF-8',11 },12 });13}
Fetching JSON
The following example shows how to fetch JSON from an origin and return it as a response.
Cloudflare Worker Snippet
JavaScript
1export default {2 async fetch(request, env, ctx) {3 /**4 * Example someHost is set up to take in a JSON request5 * Replace url with the host you wish to send requests to6 * @param {string} someHost the host to send the request to7 * @param {string} url the URL to send the request to8 */9 const someHost = 'https://examples.cloudflareworkers.com/demos';10 const url = someHost + '/static/json';1112 /**13 * gatherResponse awaits and returns a response body as a string.14 * Use await gatherResponse(..) in an async function to get the response body15 * @param {Response} response16 */17 async function gatherResponse(response) {18 const {headers} = response;19 const contentType = headers.get('content-type') || '';20 if (contentType.includes('application/json')) {21 return JSON.stringify(await response.json());22 }23 return response.text();24 }2526 const init = {27 headers: {28 'content-type': 'application/json;charset=UTF-8',29 },30 };3132 const response = await fetch(url, init);33 const results = await gatherResponse(response);34 return new Response(results, init);35 },36};
Edge Function Equivalent
JavaScript
1export async function handleHttpRequest(request, context) {2 const url = 'https://www.your-server.com/static/json';34 // Function to process the response5 async function gatherResponse(response) {6 const {headers} = response;7 const contentType = headers.get('content-type') || '';8 if (contentType.includes('application/json')) {9 return JSON.stringify(await response.json());10 }11 return response.text();12 }13 const headers = {14 'content-type': 'application/json;charset=UTF-8',15 };16 const response = await fetch(url, {17 headers,18 edgio: {19 origin: 'web', // Specify the origin defined in edgio.config.js20 },21 });2223 const results = await gatherResponse(response);2425 return new Response(results, {26 headers,27 });28}
Modify an Origin Response
The following example shows how to modify an origin response before returning it to the client, including changing the status code, adding a header, and modifying the response body.
Cloudflare Worker Snippet
JavaScript
1export default {2 async fetch(request) {3 /**4 * @param {string} headerNameSrc Header to get the new value from5 * @param {string} headerNameDst Header to set based off of value in src6 */7 const headerNameSrc = 'foo'; //"Orig-Header"8 const headerNameDst = 'Last-Modified';910 /**11 * Response properties are immutable. To change them, construct a new12 * Response and pass modified status or statusText in the ResponseInit13 * object. Response headers can be modified through the headers `set` method.14 */15 const originalResponse = await fetch(request);1617 // Change status and statusText, but preserve body and headers18 let response = new Response(originalResponse.body, {19 status: 500,20 statusText: 'some message',21 headers: originalResponse.headers,22 });2324 // Change response body by adding the foo prop25 const originalBody = await originalResponse.json();26 const body = JSON.stringify({foo: 'bar', ...originalBody});27 response = new Response(body, response);2829 // Add a header using set method30 response.headers.set('foo', 'bar');3132 // Set destination header to the value of the source header33 const src = response.headers.get(headerNameSrc);3435 if (src != null) {36 response.headers.set(headerNameDst, src);37 console.log(38 `Response header "${headerNameDst}" was set to "${response.headers.get(39 headerNameDst40 )}"`41 );42 }43 return response;44 },45};
Edge Function Equivalent
JavaScript
1export async function handleHttpRequest(request, context) {2 const headerNameSrc = 'foo';3 const headerNameDst = 'Last-Modified';45 // Fetch the original response6 const originalResponse = await fetch(request, {7 edgio: {8 origin: 'web', // Specify the origin defined in edgio.config.js9 },10 });1112 // Change status and statusText, but preserve body and headers13 let response = new Response(originalResponse.body, {14 status: 500,15 statusText: 'some message',16 headers: originalResponse.headers,17 });1819 // Change response body by adding the foo property20 const originalBody = await originalResponse.json();21 const body = JSON.stringify({foo: 'bar', ...originalBody});22 response = new Response(body, {23 headers: response.headers,24 status: response.status,25 statusText: response.statusText,26 });2728 // Add a header using set method29 response.headers.set('foo', 'bar');3031 // Set destination header to the value of the source header32 const src = response.headers.get(headerNameSrc);3334 if (src !== null) {35 response.headers.set(headerNameDst, src);36 }3738 return response;39}