http-request

This module is available to use in your EdgeWorkers code bundles to export the httpRequest() function.

HTTP sub-requests

EdgeWorkers supports HTTP requests made from within an event handler. These HTTP sub-requests provide a logical way to fetch resources asynchronously across the network. If you want your callback to wait for the sub-request to complete, the event handlers should return a Promise or be declared async.

📘

Caching features set within the delivery product also apply to the associated sub-request hostnames.

Any caching features defined for the delivery product apply to both standard URLs and sub-requests.

To use sub-requests you need an associated delivery product. Hostnames can only be requested directly when served through the Akamai network. If you don't have an associated delivery product sub-requests will fail with a 400 HTTP response code.

See the Limitations section for more information about the supported delivery products and the event handler timeouts.

👍

The Connection, Keep-Alive, Proxy-Authenticate, Proxy-Authorization, TE, Trailers, and Transfer-Encoding hop-by-hop headers should not be set when creating a request.

The Host, Content-Length, and Vary headers should not be set or copied from another request. If you opt to set them anyway, you need to make sure that the values are correct.

  • An incorrect value in the Host header can break your request.
  • An incorrect value in the Content-Length header will break the response. Make sure that the value reflects the actual length of the payload you're passing.
  • An incorrect value in the Vary header can break cacheability.

Debugging sub-requests

Extra trace information is available for debugging sub-requests. It exposes information including the sub-request status code, request timing, and rate limiting.

You can enable the enhanced sub-request trace by adding debug pragmas to your request.

httpRequest()

Exports a function from a built-in module called http-request.

httpRequest() returns a Promise that resolves to an httpResponse Object. This function is similar to fetch from the Fetch API.

These restrictions apply to when using the httpRequest function:

  • Requests made through the httpRequest() function will not trigger EdgeWorkers attached to the requested resource.
  • EdgeWorkers sub-requests only support HTTPS. If you specify another protocol in the sub-request the EdgeWorkers function will automatically convert it to HTTPS.
  • You cannot specify a port number.
  • Sub-requests made during the onClientRequest event may specify the GET, HEAD, POST, PUT, and DELETE verbs.
  • Hostnames created using automated slot matching are not supported.

📘

For more information you can also review the Limitations that apply to sub-requests.

To view debugging information for HTTP sub-requests you need to Enable enhanced debug headers. For more information review the Enhanced debug header details for HTTP sub-requests section.

Parameters

httpRequest(url [,options])
ParameterTypeDescription
urlStringThe absolute or relative URL to fetch. Relative URLs use the parent request as the base URL. The domain of a requested URL must be served by the Akamai platform. This allows the requested URL to take advantage of the features available on the Akamai platform.
httpRequest('https://[akamai servered domain]')

The options must be a JavaScript object containing at least one of the optional properties.

PropertyTypeDescription
methodStringThe HTTP request method to use. Defaults to GET, if not specified.
headersObject

Note: EdgeWorkers should not manipulate Akamai headers added for internal use. These headers typically start with 'X-Ak' and 'Akamai-'.

The HTTP request headers to include. The property names of this object are the header names. The property values are arrays containing the header values.
bodyStringContent of the request body.
timeoutIntegerTimeout value, in milliseconds, for the response to complete.
const options = {}
 
options.method = "POST"
options.headers = { "Content-Type": "application/x-www-form-urlencoded" }
options.body = "field1=value1&field2=value2"
 
const response = await httpRequest(url, options)
const response = await httpRequest(url, {
   method: "POST",
   headers: { "Content-Type": "application/x-www-form-urlencoded" },
   body: "field1=value1&field2=value2"
})
const options = {}
options.method = "GET"
options.timeout = 100

const response = await httpRequest(url, options)
const response = await httpRequest(url, {
   method: "GET",
   timeout: 100
})

This example shows how to use an asynchronous encapsulating function to call an httpRequest() function.

async function getJSON (url) {
  const response = await httpRequest(`${url}`);
  if (response.ok) {
    return await response.json();
  } else {
    return { language: 'en', greeting: 'Hello World' };
  }
}

This example shows how to use the onClientRequest event handler to call an httpRequest() function. It is also async.

import { httpRequest } from 'http-request';
import { logger } from 'log';
export async function onClientRequest(request) {
  try {
    const response = await httpRequest('/ab_test/ab.json');
    logger.log('OnClientRequest SubRequest Successful');
      if (response.ok) {
       // Add logic process response 
      }
  } catch (error) {
    logger.log('OnClientRequest SubRequest Failed: %s', error);
  }
}

httpResponse Object

The httpResponse Object defines the details of the response for the httpRequest.

Properties

body

This is the stream used to read the content body. This is a read-only ReadableStream.

export function responseProvider (request) {
 return httpRequest(`https://${request.host}${request.url}`).then(response => {
   return createResponse(

ok

This is true for 2XX response headers. This is a read-only boolean value.

const response = await httpRequest(subrequestURL);
      if (response.ok) {
...
        } else {
        ...
      }

status

The HTTP statuscode. This is a read-only integer.

// HTTP/1.1 200
  response.status;
// => 200

Methods

The following methods are available for the EdgeWorkers httpResponse objects.

getHeader()

Provides header values by header name using the same signature as the getHeader() function on callback request objects.

Parameters

getHeader(name)

Review the table for information about the available parameters.

ParameterTypeDescription
nameArray of stringsThe values of the header or a value of undefined.
response.getHeader('Content-Type')

getHeaders()

Returns an object with its own properties corresponding to the response headers.

The key is the header name normalized to lowercase and the value is an array of strings containing one string for each HTTP header with the same name. The object is mutable, but independent of the response object - meaning changes won't be reflected by response.getHeader(). The header properties are in the order that they were received by the Akamai edge servers. When you iterate across the object properties you will get the headers in the order that the browser sent them.

getHeaders() is only supported where httpRequest() is allowed.

import { httpRequest } from 'http-request';
export async function onClientRequest(request) {
    let response = await httpRequest('/example');
    request.respondWith(response.status, response.getHeaders(), "OK" );

json()

Returns a Promise that resolves to the parsed JSON response.

The response size is limited to 128 KB.

let fromOrigin = httpRequest('/endpoint.json');
let json = await fromOrigin.json();

📘

The response is buffered not streamed.

text()

Reads the body to completion and returns a Promise that resolves to a String containing the full body.

The response size is limited to 128 KB.

let fromOrigin = httpRequest('/endpoint.json');
let bodytext = await fromOrigin.text();

📘

The response is buffered not streamed.

httpResponse Headers Object

The httpResponse Headers Object provides header values by header name for the httpRequest response.

get()

This function has the same signature as the Fetch API's Header.get method.

Parameters

get(name)

Parameter

Type

Description

name

String

Returns a string with the values of the headers concatenated using the string ", ", or null if the header is not found.
For Set-Cookie headers for use response.getHeader() instead.


Did this page help you?