Edgio

JSON Responses

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';
2
3export default new Router()
4 .use(edgioRoutes)
5
6 .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 };
8
9 const content = JSON.stringify(data);
10
11 const response = new Response(content, {
12 headers: {
13 'content-type': 'application/json; charset=utf-8',
14 'x-edge-power': '9001',
15 },
16 });
17
18 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';
2
3export default new Router()
4 .use(edgioRoutes)
5
6 .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 });
8
9 // Parse the response body as JSON
10 const body = await response.json();
11
12 // Add the customer's postal_code to the json response
13 body.postal_code = context.geo.postal_code;
14
15 // 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);
19
20 return new Response(jsonBody, response);
21}