Edge functions can be used to generate JSON responses for a request. This can be useful for generating dynamic content, such as a list of products or a user profile.
Basic JSON Response
A basic JSON response can be generated by serializing a JavaScript object to a JSON string and returning it as the response body.
Router Configuration
JavaScriptroutes.js
1import {Router, edgioRoutes} from '@edgio/core';23export default new Router()4 .use(edgioRoutes)56 .match('/some/path', {7 edge_function: './edge-functions/main.js',8 });
Edge Function
JavaScriptedge-functions/main.js
1export async function handleHttpRequest(request, context) {2 const data = {3 message: 'Salutations from Edgio Functions!',4 description: 'This is a sample JSON response.',5 awesome: true,6 powerLevel: 9001,7 };89 const content = JSON.stringify(data);1011 const response = new Response(content, {12 headers: {13 'content-type': 'application/json; charset=utf-8',14 'x-edge-power': '9001',15 },16 });1718 return response;19}
Geolocation Data
Edgio Functions provides geolocation data for each request. This data can be used to customize the response based on the client’s location.
Router Configuration
JavaScriptroutes.js
1import {Router, edgioRoutes} from '@edgio/core';23export default new Router()4 .use(edgioRoutes)56 .match('/some/path', {7 edge_function: './edge-functions/main.js',8 })
Edge Function
JavaScriptedge-functions/main.js
1export async function handleHttpRequest(request, context) {2 // Forward the incoming request to the defined origin server.3 const response = await fetch(request.url, {4 edgio: {5 origin: 'web',6 },7 });89 // Parse the response body as JSON10 const body = await response.json();1112 // Add the customer's postal_code to the json response13 body.postal_code = context.geo.postal_code;1415 // Return the response and end the edge function.16 // Note: Since the original response body is read-only,17 // we must create a new response with the updated body.18 const jsonBody = JSON.stringify(body);1920 return new Response(jsonBody, response);21}