Functions@Edge (Deprecated)

Functions@Edge is undergoing end-of-life. We recommend using Edge Functions instead. Before you can get started with Edge Functions, you will need to create an Edgio Applications v7 account.

Functions@Edge, which is a Function as a Service (FaaS) solution, builds, distributes, and runs your applications on our globally distributed network. Use this solution to create serverless applications for new or existing code. Computing on the edge of our network instead of your web servers improves performance, ensures availability, allows for rapid development, and reduces your server load. Additionally, we secure your code by running it within the Deno V8 runtime.

Quickly build and deploy your applications to the edge of our network:

Quickly build and deploy your applications to the edge of our network.

Use Functions@Edge to satisfy all of your computing requirements, such as:

How Does It Work?

Once you have installed our CLI and created a credentials file, you will need to initialize your project, develop, deploy your code, and then call your function from a client application (e.g., web browser). This workflow is illustrated below.

The recommended method for iterating on code running on production traffic varies according to whether your existing client application(s) are compatible with your changes.

Requirements and Restrictions

Functions@Edge's requirements and restrictions are provided below.

We recommend that you store your Functions@Edge projects within a source control repository. Developing your functions within this type of environment allows for collaboration, tracking changes, and disaster recovery. Functions@Edge does not have any special requirements for use with a source control repository.

Quick Start

Get started by performing the following steps:

  1. Activate Functions@Edge.

    Contact your CDN account manager for information on how to activate Functions@Edge.

  2. Submit the following curl request to download and install our macOS or Linux command-line interface (CLI) application:

    curl -sLo - 'https://developer.edgecast.com/download/edgecompute/install-edge-cli.sh' | sh

    The above installation script installs the edge CLI application to $HOME/.edge/bin. Verify that this directory is defined in your system path. Alternatively, you may run the edge CLI application using the following command: $HOME/.edge/bin/edge (e.g., $HOME/.edge/bin/edge fn ps).

  3. Create an API client from within the Identity dashboard.
  4. Define your API client's credentials within a .edge.yaml file in your home directory.
  5. Initialize your project by issuing the following command and then add your code within src/main.js.

    edge fn init Project
  6. Navigate to the project's home directory and then deploy your code to our network by issuing the following command:

    edge fn up
  7. Wait a few seconds for the deployment to complete and then run your function by requesting the endpoint generated for it.

Installation

You must activate Functions@Edge prior to installation. Contact your CDN account manager for activation information.

Perform the following steps to install the Functions@Edge CLI application:

  1. Submit the following curl request to download and install our macOS or Linux command-line interface (CLI) application:

    curl -sLo - 'https://developer.edgecast.com/download/edgecompute/install-edge-cli.sh' | sh
  2. Optional. Add the following installation directory to your system path:

    $HOME/.edge/bin

    Alternatively, you may run the edge CLI application using the following command: $HOME/.edge/bin/edge (e.g., $HOME/.edge/bin/edge fn ps).

    Bash Example:

    echo 'export PATH="$PATH:/Users/jsmith/.edge/bin"' >> /Users/jsmith/.bashrc

    source /Users/jsmith/.bashrc

  3. Create an API client for Functions@Edge.

    1. From the Identity dashboard, navigate to the Clients tab.
    2. From the Assigned to Tenant option, verify that your customer account is selected.
    3. Click Create New Client.
    4. From the Name option, assign a name to this client.
    5. From the Permissions section, mark the ec.ef scope.
    6. Click Create.
    7. You will need the following information when setting up your credentials file:

      • Client ID: The ID for this client is provided from within the Client ID option on the Settings tab.
      • Secret Key: Copy this client's secret key by navigating to the Client Secrets tab and then clicking .
  4. Update the credentials file in your home directory with your credentials:

    1. From the terminal, navigate to your home directory by typing:

      cd $HOME
    2. Update .edge.yaml to include your OAuth 2.0 credentials.

      You should create this file if it does not already exist.

      Syntax:

      Example:

      identity:

        id: aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee

        secret: 1234567890Abcdefghijklmnopqrstuv

    Our CLI application will be unable to authorize your requests if the .edge.yaml file is missing, improperly formatted, or contains inaccurate OAuth 2.0 credentials.

  5. Verify that our CLI application has been properly installed by running the following command:

    edge fn ps

To update the Functions@Edge CLI to the latest version

Type the following in your terminal:

edge update

Basic CLI Functionality

Use our macOS or Linux command-line interface (CLI) application to:

Projects

A project defines key properties and it provides a centralized location for your code and supporting libraries. Initialize your project via the init command to:

To set up a project

  1. Initialize your project by navigating to the desired directory and then typing the following in a terminal:

  2. Replace the code in the main.js file with your code. Include a line that exports the function that will act as the entry point.

    By default, this function will use the name defined in step 1. If you would like to use a different alphanumeric name, update the entryPoint property within the project's edge-function.yaml file.

    Sample code excerpt:

    export default function myEdgeFunction() {
  3. Optional. Import a function from a module.

  4. Optional. Test your function on your local machine.
  5. Deploy your code by typing the following command from your project's home directory:

    edge fn up

Using Functions from our Catalog

An alternative to setting up a new project is to use a function from our catalog. These functions are ready for use or you may customize them as needed.

Common actions:

Libraries

You can import an object or value from:

Import an object or value from a module via an import statement.

Sample code excerpt (local module):

The following statement imports the cube object from src/lib/math.js:

import { cube } from "./lib/math.js";

Sample code excerpts (included library):

The following statement imports the create, getNumericDate, and verify objects from djwt/djwt.js:

import { create, getNumericDate, verify } from "edgecompute.lib/djwt/djwt.js";

The following statement imports the React object from jsx-html/react.js:

import { React } from "edgecompute.lib/jsx-html/react.js";

Request

Use the req object to retrieve data from the request.

Type Description

Get Body (ArrayBuffer)

Syntax:

req.body

Returns the request body as an ArrayBuffer object.

Example:

Converts the request body to an array of bytes:

const arrBuff = req.body;

const bytes = new Uint8Array(arrbuff);

Get Body (String)

Syntax:

req.text()

Returns a string representation of the request body.

Example:

Converts a string representation of a JSON payload to an object:

const bodyString = req.text();

const data = JSON.parse(bodyString);

Get Header

Syntax:

req.headers.get("Header")

Returns a request header's value.

Use the Headers interface of the Fetch API to perform actions on request and response headers.

Example:

Retrieves the value associated with the user-agent request header:

req.headers.get("user-agent");

Get Method

Syntax:

req.method

Returns a request's HTTP method.

Example:

The following if statement executes a block of code when the request's HTTP method is GET:

if (req.method === "GET") {

...

Get Query String Parameter (All Instances)

Syntax:

req.query.getAll("Parameter")

Returns an array of values for all instances of a query string parameter.

Use the URLSearchParams interface to perform actions on query strings.

Example:

This example assumes the following request URL:

https://example.com/index.html?info=Functions@Edge&info=Edge%20Compute

The following method returns [Functions@Edge, Edge%20Compute]:

req.query.getAll("info");

Get Query String Parameter (First Instance)

Syntax:

req.query.get("Parameter")

Returns the value for the first instance of a query string parameter.

Use the URLSearchParams interface to perform actions on query strings.

Example:

This example assumes the following request URL:

https://example.com/index.html?info=Functions@Edge&info=Edge%20Compute

The following method returns Functions@Edge:

req.query.get("info");

Get URL

Syntax:

const url = new URL(req.url);

Returns the request's URL.

Example:

This example assumes the following request URL:

https://example.com/index.html?info=Functions@Edge&info=Edge%20Compute

The following method returns a path variable set to /index.html:

const url = new URL(req.url);

const path = url.pathname;

Response

Use the res object to retrieve and manipulate the response.

Type Description

Set Header

Syntax:

res.headers.set("Header", "Value")

Sets a response header.

Use the Headers interface of the Fetch API to perform actions on request and response headers.

Example:

res.headers.set("Content-Type", "application/json");

Set HTTP Status Code

Syntax:

res.status(Status Code)

Sets the response's status code. Define a status code by passing a string or integer.

Example:

res.status(200);

Send Response

res.send(Response Body)

Sends a response.

Example:

Sends a response with Welcome! set as the response body.

res.send('Welcome!');

Chaining Response Methods

You may chain:

Status and Send Example:

export default function myEdgeFunction(req, res) {
   console.log(req.headers.get("x-header"));
   console.log(req.query.get("id"));
   console.log(req.query.getAll("env"));
   const result = cube(Math.PI);
   res.headers.set("info", "Functions@Edge");
   res.status('404').send(`Welcome to Functions@Edge! PI Cubed: ${result}`);
}

Static Assets

Your function may read assets (e.g., CSV, JSON, and JS) stored within your project's static directory.

Key information:

Reading Static Assets

Before your function may read static assets, you must first resolve the path to where they are stored by including the following import statement:

import { resolveStatic } from "edgecompute.lib/static.js"

After which, you may read an asset using a Deno namespace method.

Learn more.

Examples

Read an asset's content as an array of bytes:

const path = resolveStatic("picture.png");
const data = Deno.readFileSync(path);

Read an asset's content as a UTF-8 encoded string:

const path = resolveStatic("example.txt");
Deno.readTextFileSync(path);

Parsing a JSON file into an object:

const path = resolveStatic("sample.json");
const jsonString = Deno.readTextFileSync(path);
const myData = JSON.parse(jsonString);

Download the static-assets function from our catalog to view a sample implementation.

Testing Functions

You may test your functions:

Local Machine

Test your code locally by issuing the run command. This command serves your project's main.js file and any modules referenced by an import statement to a web server on your local machine.

Key information:

To test a function on your local machine

  1. Navigate to your project's home directory.
  2. Type the following command from within a terminal:

    edge fn run --watch
  3. Once Functions@Edge successfully compiles and starts your function's local web server, you may be prompted to allow our application to accept incoming network connect. Click Allow.
  4. Test your function by requesting http://localhost:8080 from a web browser.
  5. Review the result within your terminal.

Deploying Functions

Deploy the code associated with your project via the up command. This deployment includes your project's main.js file and any modules referenced by an import statement.

You may deploy up to 10 projects to our network. Remove outdated functions to make room for new functions.

Your code will be fully propagated after a few seconds

To deploy your code

  1. Navigate to your project's home directory.
  2. Type the following command from within a terminal:

    edge fn up
  3. Check your function's deployment status by typing the following command:

    edge fn ps

    Sample output:

    $ edge fn ps
    NAME     ENDPOINT     RUNTIME   LANGUAGE   STATUS    VERSION  CREATED         UPDATED
    myFE     https://...  default   js         deployed  v1       8 seconds ago   8 seconds ago
    
  4. Once your function's status is set to deployed, you may validate your code by requesting the endpoint associated with your function.

Listing Functions and Endpoints

Once your code has been deployed to our network, Functions@Edge will assign an endpoint to it. Use this endpoint to call your function. List all of your functions and their endpoints by performing either of the following steps:

Starting and Stopping Functions

Functions are automatically active upon their deployment. You may temporarily disable a function by issuing the following command:

edge fn stop Project

Once you have stopped a function, its endpoint will return a 503 Service Unavailable. Restart the function in order to reactivate the endpoint.

Start a function by issuing the following command:

edge fn start Project

You may also start and stop a function from within the MCC by navigating to the Functions page (ClosedHow?From the main menu, navigate to Edge Compute | Functions@Edge.), clicking on the desired function, clicking on the Actions tab, and then clicking either Start or Stop.

Removing Functions

Remove a previously deployed function from our network by issuing the following command:

edge fn rm Project

Alternatively, you may temporarily disable a function by issuing stop and start commands.

You may also remove a function from within the MCC by navigating to the Functions page (ClosedHow?From the main menu, navigate to Edge Compute | Functions@Edge.), clicking on the desired function, clicking on the Actions tab, and then clicking Remove.

Updating Functions

The workflow for updating a previously deployed function is described below.

  1. Update the code in your project's src folder as needed.
  2. Optional. Test your function on your local machine by requesting http://localhost:8080 after issuing the following command from within your project's home directory:

    edge fn run

    Learn more.

  3. Deploy the new function by issuing the following command from within your project's home directory:

    edge fn up
  4. Check deployment status by issuing the following command:

    edge fn ps
  5. Once it has been deployed, validate your updated function by requesting the corresponding endpoint.

Setting up a Function as a Serverless Origin

Deployed functions run on Functions@Edge servers. You may add a CDN layer on top of our Functions@Edge infrastructure to improve performance by caching your function's response for a short time period.

By default, our CDN caches your function's response for 7 days. Define a caching policy for your function's response by setting response headers or a Rules Engine policy.

Requirements

Serving your function through our CDN requires:

To set up a function as a serverless origin

  1. Issue the following command to verify that the desired function is in the Deployed state:

    edge fn ps
  2. Set up a customer origin group for your function.

    1. Verify that your account supports customer origin groups.

      Learn more.

    2. From within the MCC, navigate to the Origins page corresponding to the desired platform. ClosedHow?From the MCC's main menu, navigate to [HTTP Large, HTTP Small, or ADN] | Customer Origin.
    3. Click Create.
    4. Click Customer Origin.
    5. Click within the Group option and then perform the following steps:

      1. Type the nameUse the following characters when defining this name: alphanumeric, hyphens, periods, and underscores. that will be assigned to the new customer origin group.
      2. Click + Add "Customer Origin Group Name".
    6. In the Name option, type the nameUse the following characters when defining this name: alphanumeric, hyphens, periods, and underscores. by which you will identify this function.
    7. From the Edge Function option, select the function identified in step 1.

      If you do not see the Edge Function option, perform step 1 again to verify that you have at least one function in the Deployed state.

    8. Optional. Click Origin TLS from the Group Settings section. Verify that the Use SNI for HTTPS Origin Requests option is enabled.

    9. Click Save to save your customer origin group.
  3. Use the Certificate Provisioning System to request a DV, OV, or EV certificate for the hostname through which your function will be requested.

    Learn more.

    Sample hostnames:

    function.edgecast.com | myfunction.example.com | optimize.example.com
  4. Create an edge CNAME configuration that points the hostname identified in step 3Sample hostnames: cdn.example.com, function.example.com, and function.edgecast.com to the customer origin group created in step 2 (e.g., /800001/myfunction).

    Learn more.

  5. Optional. Define a caching policy for your function's response by setting response headers or a Rules Engine policy.

    • Response Headers: Set the Cache-Control header, Expires header, or both within your function.

      Redeploy your function to apply your changes to production.

      Example:

      res.headers.set('Cache-Control', 'max-age=5')
      
    • Rules Engine: Deploy a policy that defines how your function's response will be cached by our CDN.

      By default, the External Max-Age feature overwrites Cache-Control and Expires headers defined within your function.

      Learn more.

      Example:

      The following rule caches requests to a function for 5 seconds:

  6. Wait until you can verify that your certificate is live.

    Learn more.

  7. Create or update a CNAME record within your DNS zone to point the hostname identified in step 3 to your certificate's target CNAME.
  8. Verify that your function can now be served through our CDN by submitting a HTTPS request for the hostname identified in step 3.

    Example:

    If you requested a certificate for functions.edgecast.com, then you should request this URL:

    https://functions.edgecast.com

Reports

Use our reports to gain insights into your function's usage. We offer the following types of reports:

To view reports for your function

  1. From within the MCC, navigate to the Functions page. (ClosedHow?From the main menu, navigate to Edge Compute | Functions@Edge.)
  2. Click on the desired function.
  3. Click on the Reports tab.
  4. From the top of the Reports page, select one of the following time periods:

    Time Period Start Date/Time

    End Date/Time

    Time Interval

    Last hour

    An hour ago at the current time (UTC)

    Today at the current time (UTC)

    5 minutes (300 seconds)

    Last 24 hours

    24 hours ago at the current time (UTC)

    Today at the current time (UTC)

    5 minutes (300 seconds)

    Last 7 days

    A week ago at the current time (UTC)

    Today at the current time (UTC)

    1 day (86,400 seconds)

    Last 30 days

    30 days ago at the current time (UTC)

    Today at the current time (UTC)

    1 day (86,400 seconds)

    Last 90 days

    90 days ago at the current time (UTC)

    Today at the current time (UTC)

    1 day (86,400 seconds)

    A request will be included in the report when the response is sent at or after the start date/time and before the end date/time.

Troubleshooting

Basic troubleshooting information is provided below.

Issue Steps

Authentication error

fn up

An authentication error typically indicates that Functions@Edge could not find valid credentials. Perform the following steps:

  1. Verify that your home directory contains the credentials file (.edge.yaml).
  2. Verify the spacing within your .edge.yaml file.
  3. Verify the client ID and the secret defined in the .edge.yaml file match the credentials generated for Functions@Edge.

Syntax error

fn up

The following error indicates that we detected a syntax error:

begin processing: myFunction
------------
main.js: Line #:Column #Error Message

For example, the following error indicates that an undefined variable was detected:

begin processing: myFunction
------------
main.js: 4:14  'myUndefinedVar' is not defined.
2    console.log(req.headers.get("x-header"));
3
4    console.log(myUndefinedVar);
                 ^^^^^^^^^^^^^^

Review your code. Once you have fixed the issue, attempt to deploy your function again.

General troubleshooting

fn up

Perform the following steps when experiencing issues with fn up:

  1. Check that you are in the project's home directory.
  2. Verify that the entryPoint property in the edge-function.yaml file matches the named function within the main.js file.
  3. Verify that the srcFolder property in the edge-function.yaml file points to a directory that contains the main.js file.

Function not deployed

fn ps

If your function's state is Not Deployed, you should issue the following commands to remove and then redeploy it:

edge fn rm myProject

edge fn up

Function not found

Our service returns a 404 Not Found with the following response body when requesting a function that does not exist:

Function not found

Perform the following steps:

  1. Issue the following command to view a list of your functions:

    edge fn ps
  2. Verify that the function is in the deployed state.

    • If the function is in the deployed state, compare the requested URL with the function's endpoint.
    • If the function is in a different state, then you should issue the following commands to remove and then redeploy it:

      edge fn rm myProject

      edge fn up

    • If the function is not listed, then issue the following command within the project's home directory to deploy it:

      edge fn up
  3. Request your function's endpoint to verify that it is now functional.

Log Data

If you are still experiencing issues, view log data for that project by issuing the following command:

edge fn logs Project

Verify Installation

If you cannot identify the issue from the log data, issue the following command to update your client to the latest version:

edge update

Verify that you are using the latest Functions@Edge build by issuing the following command:

edge version

Reference

Reference information for commands, flags, and Functions@Edge locations is provided below.

Commands

Functions@Edge commands are described below.

Command Description

completion

Outputs a completion script for the edge CLI application. Use this script to enable autocompletion for edge CLI commands.

Syntax:

edge completion [bash|zsh|fish|powershell]

Key information:

  • Completion requires a shell completion system (e.g., bash-completion). If one has not been installed or activated within your shell, then you will need to do so before you can use completion.
  • You may load completions for all sessions or just the current one.

    Refer to your shell's documentation to find out how to set up completions.

    Example:

    Load edge CLI completions for all bash sessions through the following command:

    source <(edge completion bash)

fn

Manage your functions by passing a function-specific subcommand.

help

View help information for commands and flags.

update

Updates the edge CLI application to the latest version.

version

View client and server version information.

Function-Specific Subcommands

Use the following syntax to pass a function-specific subcommand:

edge fn Subcommand

Function-specific subcommands are described below.

Command Description

catalog

Retrieve a list of functions within our catalog by issuing the following command:

edge fn catalog

Download a function from our catalog by issuing the following command:

edge fn catalog init Function

info

View information about a specific project, such as its endpoint, performance, location-specific status information, and version history.

Syntax:

edge fn info Project

init

Creates a project for your function. Specifically, it creates a project configuration file (edge-function.yaml) and a src folder that contains a sample project.

Syntax:

edge fn init Project

logs

View log data for a specific function.

Log data is limited to the last 4 hours and 1,000 lines.

Syntax:

edge fn logs Project

Pass the -n or --num flag to restrict the number of log lines that will be returned.

edge fn logs -n # Project

Example:

Returns the 10 most recent log lines for myProject:

edge fn logs -n 10 myProject

promote

Deploys the specified version of your project. Promoting a version replaces the current version of your project.

Use info to find out which version of your project is currently active.

Syntax:

edge fn promote Project Version

Example:

edge fn promote myProject v1

ps

View the following information for each deployed function:

  • NAME: Indicates the name of the project corresponding to your function.
  • ENDPOINT: Indicates the endpoint through which you may access your function. If your function has not been deployed, then this field will report PENDING.
  • RUNTIME: Returns default.
  • LANGUAGE: Indicates the function's programming language. Returns js.
  • STATUS: Indicates the function's current state. Valid values are:

    deployed | deploying | not deployed | starting | stopping | stopped | building | build failed | removing | compile failed

    The not deployed state typically indicates that an error occurred with the deployment. Remove that function and try issuing another up command for that project.

  • VERSION: Indicates your function's version number. Version information is incremented whenever you upload a new version of your function.
  • CREATED: Indicates when the project was first deployed.
  • UPDATED: Indicates when the project was last deployed.

Syntax:

edge fn ps

rm

Removes a specific function from our network.

Syntax:

edge fn rm Project

run

Starts a local web server for a specific function.

Use this mode to test a function locally before deploying it to the production environment.

Learn more.

Syntax:

edge fn run

By default, this command uses port 8080. Override this behavior by passing the --port flag set to the desired port:

edge fn run --port 8020

Automatically compile and start a local web server for this function whenever it is updated by passing the --watch flag:

edge fn run --watch

start

Starts a function.

Use this command to restart a previously stopped function.

Syntax:

edge fn start Project

stop

Stops a function. Once a function has been stopped, requests to the function's endpoint will no longer be honored.

Syntax:

edge fn stop Project

up

Deploys a function to our network. This command must be issued from the project's home directory.

Syntax:

edge fn up

By default, this command will not update a project when changes to your code are not detected. Override this behavior by passing the --force flag:

edge fn up --force

vendor

Experimental

Adds support for a third-party library to a function.

Third-party library support through this experimental feature is currently restricted to lodash.

Syntax:

edge fn vendor Command

Subcommands:

Pass one of the following commands:

  • add: Declares a dependency for your function by generating an entry to an import map for the desired library.

    Example:

    Declares a lodash dependency for your function.

    edge fn vendor add lodash
  • init: Adds dependencies in bulk to your project by parsing import statements or package.json.

    Example:

    edge fn vendor init

Flags

Our CLI supports the following flags:

Flag Description

--config

Set a new credential file. By default, your credentials are stored at:

$HOME/.edge.yaml

Syntax:

edge --config Path/FileName

-h, --help

Returns help information for a specific command or subcommand.

Example:

edge fn ps --help

Regions

Functions are automatically deployed to North America, Europe, and Asia.