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:
Use Functions@Edge to satisfy all of your computing requirements, such as:
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.
Functions@Edge's requirements and restrictions are provided below.
Language: JavaScript
Functions@Edge does not support the use of callbacks within your function. However, you may request your function's endpoint through a callback.
Active Functions: You may have up to 10 functions in the Deployed state.
Use the stop command to temporarily disable a function. Functions in the stopped state do not count towards this limit.
Alternatively, use the rm command to remove obsolete functions.
Memory: Each function is restricted to 128 MB per container.
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.
Get started by performing the following steps:
Activate Functions@Edge.
Contact your CDN account manager for information on how to activate Functions@Edge.
Submit the following curl request to download and install our macOS or Linux command-line interface (CLI) application:
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).
Initialize your project by issuing the following command and then add your code within src/main.js.
Navigate to the project's home directory and then deploy your code to our network by issuing the following command:
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:
Submit the following curl request to download and install our macOS or Linux command-line interface (CLI) application:
An alternative to using the installation script is to manually download and install our CLI application.
Perform the following steps:
macOS Only
Perform the following steps to add the Functions@Edge CLI application as an exception to your security settings:
Move our CLI application to a directory in your system path.
Sample Directory:
From the terminal, navigate to the above directory and then run the following command to allow our CLI application to execute as a file:
Optional. Add the following installation directory to 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).
Bash Example:
echo 'export PATH="$PATH:/Users/jsmith/.edge/bin"' >> /Users/jsmith/.bashrc
source /Users/jsmith/.bashrc
Create an API client for Functions@Edge.
You will need the following information when setting up your credentials file:
Update the credentials file in your home directory with your credentials:
From the terminal, navigate to your home directory by typing:
Update .edge.yaml to include your OAuth 2.0 credentials.
You should create this file if it does not already exist.
Syntax:
identity:
id: Client IDA value that uniquely identifies this client application and your customer account.
secret: SecretThis value authenticates the client application identified above.
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.
Verify that our CLI application has been properly installed by running the following command:
To update the Functions@Edge CLI to the latest version
Type the following in your terminal:
Download the CLI application.
macOS Only
Perform the following steps to add the Functions@Edge CLI application as an exception to your security settings:
Move our CLI application to a directory in your system path.
Sample Directory:
From the terminal, navigate to the above directory and then run the following command to allow our CLI application to execute as a file:
Verify that you have properly installed the latest version of our CLI application by running the following command:
Verify that the client and server report the same version (e.g., 1.8.2).
Version SHA Built Client: v1.8.2 512be5614f64668750029da631a49e03d3493294 2022-07-01T17:08:39Z Server: v1.8.2 512be5614f64668750029da631a49e03d3493294 2022-07-01T17:55:39Z
Use our macOS or Linux command-line interface (CLI) application to:
Initialize a project.
edge fn init Project
Deploy your functions.
edge fn up
Stop or resume a function.
edge fn stop Project edge fn start Project
Remove previously deployed functions.
edge fn rm Project
View status information for each function.
edge fn ps
View a function's log data.
edge fn logs Project
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:
Generate a configuration file called edge-function.yaml. Its core properties are described below.
Property | Description |
---|---|
entryPoint |
Identifies a function within your main.js file that will act as the entry point. This property's value and the name of your function may only consist of alphanumeric characters. |
jsConfig |
Reserved for future use. |
language |
Identifies the programming language in which your code was written. The only valid value is: js
|
name |
Identifies your project by name. |
runtime |
Set to default. |
srcFolder |
Identifies the relative path to the directory that contains your main.js file. |
Sample configuration file:
entryPoint: myEdgeFunction jsConfig: {} language: js name: GetStatus runtime: default srcFolder: ./src
Initialize your project by navigating to the desired directory and then typing the following in a terminal:
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:
Optional. Import a function from a module.
Deploy your code by typing the following command from your project's home directory:
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:
Retrieve a list of all functions in our catalog:
Download a function from our catalog into the current directory:
Deploy a catalog function:
Deploy the function by issuing the following command from the directory that contains the edge-function.yaml file:
Check deployment status by issuing the following command:
You can import an object or value from:
An included library.
Our included libraries (e.g., jsx-html/react.js and djwt/djwt.js) are limited to the objects leveraged in our sample projects. Download our sample projects from our catalog.
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:
Sample code excerpts (included library):
The following statement imports the create, getNumericDate, and verify objects from djwt/djwt.js:
The following statement imports the React object from jsx-html/react.js:
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");
|
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; |
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!');
|
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}`); }
Your function may read assets (e.g., CSV, JSON, and JS) stored within your project's static directory.
Key information:
You must store all of your static assets within the following directory:
Your project's srcFolder is defined within its configuration file (edge-function.yaml).
Default Path:
Resolve the path to a static asset using resolveStatic. Absolute or relative paths are unsupported.
An absolute or relative path may work when testing locally. However, absolute or relative paths will not resolve correctly for deployed functions.
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.
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.
You may test your functions:
After deployment by requesting the function's endpoint through a tool, such as curl, Postman, or a web browser.
An alternative to using one of the above tools is to submit GET, POST, and DELETE requests to your function's endpoint from within the MCC. Test your function from within the MCC by navigating to the Functions page ( ), clicking on your function, and then clicking on the Test tab.
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:
If an error occurs while compiling your function, then it will be reported within the terminal. Review and update your code. After which, reissue this command.
Example:
running helloworld locally, watch: true, port: 8080 ⣾ uploading for compilation ✓ ⢿ compiling function ✗ ------------ main.js: 14:3 'fres' is not defined. 12 console.log(req.headers.get("x-header")); 13 res.headers.set('x-set', 'wow') 14 fres.headers.append("x-append", "foo"); ^^^^ 15 res.headers.append("x-append", "bar");
Allow our application to accept incoming network connections if prompted upon starting your function's local web server.
macOS example:
Submit a GET request to your local machine to test your function.
Example:
The terminal displays the result for each request to your function.
Example:
null [] null GET localhost:8080 / 200 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Client IP: null { headers: { "x-append": "foo, bar", "x-set": "wow" }, status: 200, type: "string", result: "Welcome to the Edge! PI Cubed: 31.006276680299816" }
To test a function on your local machine
Type the following command from within a terminal:
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
Type the following command from within a terminal:
Check your function's deployment status by typing the following command:
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
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:
Command Line: Type the following command in the terminal:
Quickly test your function by pasting your function's endpoint in a browser's address bar and then pressing ENTER.
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
MCC: Navigate to the Functions page. ( ) This page lists all of your functions and key information, such as version information, their current status, and when they were last updated.
Click on a function to manage, test, or view detailed function information. View reports on function usage from within the Reports tab.
Functions are automatically active upon their deployment. You may temporarily disable a function by issuing the following command:
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:
You may also start and stop a function from within the MCC by navigating to the Functions page ( ), clicking on the desired function, clicking on the Actions tab, and then clicking either Start or Stop.
Remove a previously deployed function from our network by issuing the following command:
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 ( ), clicking on the desired function, clicking on the Actions tab, and then clicking Remove.
The workflow for updating a previously deployed function is described below.
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:
Deploy the new function by issuing the following command from within your project's home directory:
Check deployment status by issuing the following command:
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.
Serving your function through our CDN requires:
A CDN account that supports customer origin groups.
If your account has not been updated to use customer origin groups, contact your CDN account manager to upgrade.
Find out whether your account supports customer origin groups.
End-to-end HTTPS encryption with Server Name Indication (SNI) enabled.
HTTPS encryption requires requesting a TLS certificate, setting up an edge CNAME configuration, and defining a CNAME record.
To set up a function as a serverless origin
Issue the following command to verify that the desired function is in the Deployed state:
Set up a customer origin group for your function.
Verify that your account supports customer origin groups.
Click within the Group option and then perform the following steps:
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.
Optional. Click Origin TLS from the Group Settings section. Verify that the Use SNI for HTTPS Origin Requests option is enabled.
Use the Certificate Provisioning System to request a DV, OV, or EV certificate for the hostname through which your function will be requested.
Sample hostnames:
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).
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.
Example:
The following rule caches requests to a function for 5 seconds:
Wait until you can verify that your certificate is live.
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:
Use our reports to gain insights into your function's usage. We offer the following types of reports:
Requests (RPS)
This line graph measures the rate at which this function was requested.
Formula:
Each data point is calculated using the following formula:
Example:
If you generate a report for the Last Hour, then the time interval for each data point is 300 seconds. If your function was requested 900 times within one of those time intervals, then the rate for that data point is 3 requests per second.
HTTP Status Code (RPS)
This line graph measures the frequency (requests per second) at which our service responds with specific HTTP status codes (e.g., 200, 400, and 500) for this function.
Formula:
Each data point is calculated using the following formula:
Example:
If you generate a report for the Last Hour, then the time interval for each data point is 300 seconds. If our service returned a 200 OK 900 times within one of those time intervals, then the rate of 200 OK responses for that data point is 3 per second.
Average Response Time (Milliseconds)
This line graph measures the average response time, in milliseconds, for this function.
Formula:
Each data point is calculated using the following formula:
Example:
If you generate a report for the Last Hour, then the time interval for each data point is 300 seconds. If our service spent 900,000 milliseconds processing this function within one of those time intervals, then the average response time for that data point is 3,000 milliseconds.
Data Transferred (BPS)
This line graph measures the rate, in bytes per second, for the data that our service received (ingress) or delivered (egress) as a result of this function.
Formula:
Each data point is calculated using the following formula:
Example:
If you generate a report for the Last Hour, then the time interval for each data point is 300 seconds. If 9,000 bytes were received or delivered as a result of this function within one of those time intervals, then the data transferred rate for that data point is 30 bytes per second.
To view reports for your function
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.
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:
|
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:
|
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:
|
If you are still experiencing issues, view log data for that project by issuing the following command:
If you cannot identify the issue from the log data, issue the following command to update your client to the latest version:
Verify that you are using the latest Functions@Edge build by issuing the following command:
Reference information for commands, flags, and Functions@Edge locations is provided below.
Functions@Edge commands are described below.
Command | Description |
---|---|
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:
|
|
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. |
Use the following syntax to pass a function-specific subcommand:
Function-specific subcommands are described below.
Command | Description |
---|---|
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
|
|
View information about a specific project, such as its endpoint, performance, location-specific status information, and version history. Syntax: edge fn info Project
|
|
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
|
|
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
|
|
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
|
|
View the following information for each deployed function:
Syntax: edge fn ps
|
|
Removes a specific function from our network. Syntax: edge fn rm Project
|
|
Starts a local web server for a specific function. Use this mode to test a function locally before deploying it to the production environment. 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
|
|
Starts a function. Use this command to restart a previously stopped function. Syntax: edge fn start Project
|
|
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
|
|
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
|
|
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:
|
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
|
Functions are automatically deployed to North America, Europe, and Asia.