Request Object

The request object represents the HTTP request. It contains properties that provide details and context about the request, as well as properties that allow for modifying the request.

Properties

body

A stream used to read the contents of the request body. This is a read-only ReadableStream value.

This property is only available when using the responseProvider event.

const opt = {
   "method": "POST",
   "body": request.body.pipeThrough(new TextEncoderStream())
}
let response = await httpRequest(url, opt);

method

The HTTP method of the incoming request. This is a read-only string value.

// GET /search?q=something
request.method
// => "GET"

scheme

The scheme of the incoming request ("http" or "https"). This is a read-only string value.

// https://www.example.com/search?q=something
request.scheme
// => "https"

host

The host header value of the incoming request from the client. This is a read-only string value.

// Host: www.example.com
request.host
// => "www.example.com"

path

The URL path of the incoming request, including the filename and extension, but without a query string. This is a read-only string value.

// https://www.example.com/search?q=something
request.path
// => "/search"

query

The query string of the incoming request. This is a read-only string value.

// GET /search?q=something
request.query
// => "q=something"

url

The relative path and query string of the incoming request. This is a read-only string value.

// https://www.example.com/search?q=something
request.url
// => "/search?q=something"

cpCode

A unique identifier in the form of an unsigned integer that is used for reporting site traffic usage data. This is a read-only value.

// Request cpCode 12345
 request.cpCode
// => 12345

userLocation

Returns an object that contains properties specifying the geographic location.

For more information see the User Location Object.

device

Returns an object that contains properties specifying the client device characteristics.

For more information see the Device Object.

cacheKey

Returns the methods that specify the HTTP response in cache for an HTTP request.

For more information see the CacheKey Object.

Methods

The following methods are available for the EdgeWorkers Request objects.

Methods

onClient Request

onOrigin Request

onOrigin Response

onClient Response

response Provider

respondWith()

addHeader()

getHeader()

getHeaders()

setHeader()

removeHeader()

getVariable()

setVariable()

route()

text()

json()

respondWith()

Constructs a response for the given request, rather than fetching a response from cache or the origin.

Returns - Responses created through the respondWith() method can return a body with a maximum of 2048 characters.

👍

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.

📘

respondWith() supports the GET, POST, DELETE, PUT, PATCH, and HEAD request methods.

Parameters

respondWith(status, headers, body, [deny_reason])

Review the table for information about the available parameters. This method can only be modified during the onClientRequest and onClientResponse events.

ParameterTypeDescription
statusIntegerHTTP status code

Note: The status supports 2xx Success , 3xx Redirection , 4xx Client Error , and 5xx Server Error status codes. An exception is thrown if the status code is outside the 2xx to 5xx range.)

headersObjectProperties used as key:value pairs for the response header
bodyStringContent of the response body
deny_reasonString(optional) Deny reason when the status code is a 403

📘

You cannot add a "SetCookie" object to the request.respondWith() header. Other response headers are supported.

📘

If you apply EdgeWorkers and an Edge Redirect Cloudlet to the same end user request, the Cloudlet cannot set the Location header when the EdgeWorker runs a respondWith() method.

// generate an empty API response
request.respondWith(200, {'Content-Type': ['application/json;charset=utf-8']  }, '{}');
// => {}
// generate a denied API response
request.respondWith(403, {'Content-Type': ['application/json;charset=utf-8']  }, '{}', 'Denied Response');
// => {}

addHeader()

Renames or adds values to a header. If the header already exists, then the value is appended. The new header value can be a single string or an array. This request header can only be modified during the onClientRequestand onOriginRequestevents.

Parameters

addHeader(name, value)

Review the table for information about the available parameters.

ParameterTypeDescription
nameStringNew header name
valueString or ArrayNew Header value(s)
//
request.addHeader('HeaderName', 'HeaderValue');
// HeaderName: HeaderValue

getHeader()

Returns an array of header values by header name. The header names are case insensitive. If the header doesn't exist, a value of undefined is returned. This request header can only be modified during the onClientRequestand onOriginRequestevents.

Parameters

getHeader(name)

Review the table for information about the available parameters.

ParameterTypeDescription
nameArray of stringsName of the header(s)
// User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:66.0) Gecko/20100101 Firefox/66.0
request.getHeader('User-Agent')[0];
// => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:66.0) Gecko/20100101 Firefox/66.0"

getHeaders()

Returns a JavaScript object that contains all HTTP request headers as properties.

The key for each property is the name of the HTTP header, normalized to lower-case. The value is an array of strings, containing one string for each HTTP header with the same name. 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.

👍

Refer to the code sample for the Redirect Liquidator use case in the EdgeWorkers GitHub repo for more information about how to use and debug getHeaders().

This method can only be called during the responseProvider event.

import { httpRequest } from 'http-request';
import { createResponse } from 'create-response';
export function responseProvider(request) {
    let hdrs = request.getHeaders();
    httpRequest('/header-collector', {headers: hdrs});

    //...
}

setHeader()

Sets header values and overrides any previous headers. This request header can only be modified during the onClientRequest and onOriginRequest events.

Parameters

setHeader(name, value)

Review the table for information about the available parameters.

ParameterTypeDescription
nameStringName of the header
valueStringValue of the header

📘

EdgeWorkers cannot manipulate Akamai headers added for internal use. These headers typically start with 'X-Ak' and 'Akamai-'.

// Referer: http://www.example.com
request.setHeader('Referer', 'http://www.akamai.com');
// Referer: http://www.akamai.com

removeHeader()

Removes the named header. This request header can only be modified during the onClientRequest and onOriginRequest events. The header name is case insensitive.

Parameters

removeHeader(name)

Review the table for information about the available parameters.

ParameterTypeDescription
nameStringName of the header to remove
// Pragma: HeaderName
request.removeHeader('Pragma');
//

getVariable()

Gets the value of a Property Manager user-defined variable. Only variables that start with a PMUSER_ prefix are available. The name of the variable must be UPPERCASE.

Parameters

getVariable(name)

Review the table for information about the available parameters.

Parameters

Type

Description

name

String

Names of the user-defined variables

If no variables exist, a value of undefined is returned.

📘

PMUSER_ variables with a security setting of sensitive are not available within an EdgeWorkers function using getVariable.

request.getVariable('PMUSER_MYVARIABLE');
// => "MyVariableValue"

setVariable()

Sets the value of a Property Manager user-defined variable. Only variables that start with a PMUSER_ prefix are available. The name of the variable must be UPPERCASE.

The total size limit when creating Property Manager user-defined variables is 1024 characters. This limit includes the name and value of the variable and only applies to EdgeWorkers added or modified using the JavaScript API.

The 1024 character limit is a modification limit that only applies to setVariable, not getVariable. For example, if you use advanced metadata to create a PMUSER_ variable in a property with a value that exceeds 1024 characters, the EdgeWorkers function can still read the value.

If however, you then wanted to modify that variable, you could do so up to 1024 characters (including the name and value of the variable). This 1024 limit is cumulative for all setVariable calls in the execution of a given event. If you exceed the limit, setVariable will throw an exception.

Parameters

setVariable(name, value)

📘

PMUSER_ variables with a security setting of sensitive are not available within an EdgeWorkers function using setVariable.

By default, the security settings of the PMUSER_ variable are hidden. Hidden security settings are not available in the X-Akamai-Session-Info response headers if requested.

Review the table for information about the available parameters.

ParameterTypeDescription
nameStringNames of the user-defined variables to set
valueStringValue to assign to the variable
// PMUSER_MYVARIABLE = "MyValue"
request.setVariable('PMUSER_MYVARIABLE','MyNewValue');
// => PMUSER_MYVARIABLE = "MyNewValue"

route()

Routes the outbound origin request to a pre-defined origin server, a modified path, or a modified query string. The destination must be a JavaScript object containing at least one of the following optional properties; path, query, or origin. If the destination is not a JavaScript object an error is thrown. This method can only be modified during the onClientRequest event.

Parameters

route(destination)

📘

Edge defined redirects always take precedence over modify forward paths. Therefore, the Edge Redirector and Redirect behaviors take precedence over EdgeWorkers forward route modifications made using the route(destination) function.

Review the table for information about the available parameters.

ParameterTypeDescription
destinationObjectA JavaScript object containing the optional properties. An error is thrown if the input is not a JavaScript Object.

Review the table below for information about the optional properties.

PropertiesTypeDescription
pathStringNew path for the outbound origin request.

Include the complete URI path beginning with a forward slash (/). If the URI includes a filename, the file extension is also required.

This setting overrides any previously defined Property Manager behaviors that attempt to set the forward path.

Note: A Property Manager behavior that attempts to set the forward path after the EdgeWorker runs will override this EdgeWorkers setting.

queryStringNew query string for the outbound origin request.
originStringNew outbound origin request to a preconfigured origin identifier in the delivery property.

Note: See Set up a Conditional Origin Group rule in the Cloudlets documentation for instructions on how to set up the origins to use with your EdgeWorkers.

📘

You may have origins that produce different content for the same URL. When you are changing this kind of origin you need to ensure that you use the origin server hostname in the cache key. For more information see the Cache Key Hostname documentation.

// GET /search?q=something
request.route({origin: "origin-1", path: "/example.html", query: "a=1&b=2"}); 
// GET /example.html?a=1&b=2

text()

Reads the body to completion and returns a promise that resolves to a string containing the full body. The request is decoded as UTF-8, using the replacement character on encoding errors.

The maximum request size is 16 KB. If the request exceeds this limit the promise is rejected.
This method can only be called during the responseProvider event.

import { createResponse } from 'create-response';
 
export async function responseProvider (request) {
    let mybody = await request.text();
    return createResponse(200,
                          { 'request-body': [mybody] },
                           '<html><body><p>Hello World</p></body></html>'
                         );
}

📘

The request is buffered, not streamed.

json()

Reads the body to completion. Returns a promise that resolves to an Object that is a result of parsing the body JSON.

The maximum request size is 16 KB. If the request exceeds this limit the promise is rejected.
This method can only be called during the responseProvider event.

import {createResponse} from 'create-response';
export async function responseProvider (request)  {

        let mybody = await request.json();
        return createResponse(200, {}, JSON.stringify(mybody));
}

📘

The request is buffered, not streamed.


Did this page help you?