Introducing Edgio Applications v7Find out what's new.
Edgio
Edgio

Getting Started with CDN-As-Code (EdgeJS)

Upgrading from Edgio Applications version 6 or earlier may require significant changes to your CDN-as-code configuration as certain core legacy components have limited support. View our upgrading guide.
Edgio provides a CDN-as-code platform that allows you to configure CDN behavior using EdgeJS within a file (routes.[js|ts]) stored alongside your code. This allows you to leverage the power of source control for collaboration and to link your CDN configurations with specific versions of your web application.

Quick Start

Get started with CDN-as-code by either experimenting with:

Create a Property

Create a property. If you have already performed this step, proceed to the next step. Learn more.

Initialize Your Property

Use the Edgio CLI to initialize your property. If you have already performed this step, proceed to the next step.
This step requires Node.js v16.x.
Install the Edgio CLI, initialize your property, and then deploy it by running the following command from the root directory of your web application or website:
Bash
1npx @edgio/cli@latest init \
2 --edgioVersion latest \
3 --name <PROPERTY> \
4 --deploy
Replace <PROPERTY> with the name of the property defined in step 1. You should only use lower-case characters and replace spaces with dashes (e.g., my-property).
When you run the above command, the CLI will prompt you with the following questions to set up your property:
text
1🚀 Let's get started with Edgio!
2
3 ✔ What is the hostname or IP address of the origin site that you will host on Edgio? … my-custom-property.com
4 ✔ Should we create a new directory for your Edgio app or use the current directory? › Create a new directory
5 ✔ Which package manager would you like to use? › npm
6 ✔ installing @edgio/core, @edgio/cli, @edgio/prefetch, @edgio/devtools... done.
7 > edgio.config.js not found, creating...
8 > routes.js not found, creating...
9 🔑 You are not logged in.
10
11 ? To log you in we're going to open your browser and visit Edgio Developer Console. › - Use arrow-keys. Return to submit.
12 ❯ Continue
13 Cancel
First, you will be prompted to enter the hostname or IP address of the origin site that you will host on Edgio. This is the site that Edgio will fetch content from. For example, if you are using Edgio to improve the performance of my-custom-property.com, then you would enter my-custom-property.com here.
Next, you will be prompted to choose whether to create a new directory for your Edgio property or use the current directory. If you are currently in the root directory of your project code, then choose Use the current directory.
Finally, you will be prompted to choose which package manager to use, either npm or yarn.
If this is your first time using the Edgio CLI to deploy, then you will be prompted to log in to the Edgio Console. To log in, select Continue. This will open a browser window where you may log in by creating a new account, or authenticating with a third-party provider such as Google or GitHub. Once you log in, you’ll be prompted to authorize creating a local access token:
Local Access Token
After clicking Create access token, you may return back to the CLI and continue with the deployment.
This step is necessary to deploy your property to Edgio, but not necessary to run and build your property locally. It is recommended you authenticate during this step otherwise your first deployment will fail.
Once your deployment completes, you should see an output similar to the following:
text
1🚀 Let's get started with Edgio!
2
3 ✔ What is the hostname or IP address of the origin site that you will host on Edgio? … my-custom-property.com
4 ✔ Should we create a new directory for your Edgio app or use the current directory? › Create a new directory
5 ✔ Which package manager would you like to use? › npm
6 ✔ installing @edgio/core, @edgio/cli, @edgio/prefetch, @edgio/devtools... done.
7 > edgio.config.js not found, creating...
8 > routes.js not found, creating...
9 🔑 You are not logged in.
10
11 ✔ To log you in we're going to open your browser and visit Edgio Developer Console. › Continue
12 Authenticating user!
13 Please visit this URL from any device and click on "Create access token" to authorize this device:
14 https://api.edgio.app/account/cli?name=CLI+Api+Key&sid=<ID>&action=deploy
15
16 Waiting for authentication...
17 🔑 You are now logged in as "xxx@yyy.zzz"
18
19 📋 Deploying to:
20 > Team: Private space
21 > Site: my-custom-property.com
22 > Environment: default
23 > Edgio version: 7.0.12
24 > Deployment #1
25
26 🛠️ Building your app for deployment on Edgio
27 > Bundling router... done.
28 > Bundling edge functions... done.
29 > Writing static asset aliases... done.
30 done 277ms
31
32 📦 Packaging...
33 > Zipping project folder
34 > Size: 674.22 KB
35 done 177ms
36
37 📡️ Uploading...
38 done 1s
39
40 ⌛ Deploying...
41 done 56s
42
43 ***** Deployment Complete *****************************************************
44 * *
45 * 🖥 Edgio Developer Console: *
46 * https://edgio.app/<YOUR-TEAM>/my-custom-property.com/env/default/builds/1 *
47 * *
48 * 🔗 Permalink: *
49 * https://<YOUR-TEAM>-my-custom-property-com-1.free.edgio-perma.link *
50 * *
51 * 🌎 Edge: *
52 * https://<YOUR-TEAM>-my-custom-property-com-default.edgio.link *
53 * *
54 *******************************************************************************
55
56 To change directories to your new Edgio app:
57
58 cd my-custom-property.com
59
60 To run your app locally:
61
62 edg dev
63
64 To redeploy your app:
65
66 edg deploy

Edgio Files

During the initialization process, the Edgio CLI created the following files:
  • edgio.config.js: This file contains the configuration for your Edgio property. You can use this file to configure your property’s name, environments, origins, and other settings. Learn more.
  • routes.[js|ts]: This file contains the router rules for your Edgio property. You can use this file to define how Edgio will handle requests to your property.

Config File

The edgio.config.js file contains some configurations the router may reference for handling requests along with other components such as connectors.
The default edgio.config.js file contains the following configuration based on the input from out initialization process:
JavaScript
1// This file was automatically added by edgio init.
2// You should commit this file to source control.
3// Learn more about this file at https://docs.edg.io/guides/edgio_config
4module.exports = {
5 // The name of the site in Edgio to which this app should be deployed.
6 name: 'my-custom-property.com',
7
8 // The name of the team in Edgio to which this app should be deployed.
9 // team: 'my-team-name',
10
11 // Overrides the default path to the routes file. The path should be relative to the root of your app.
12 // routes: 'routes.js',
13
14 origins: [
15 {
16 // The name of the backend origin
17 name: 'origin',
18
19 // Uncomment the following to override the host header sent from the browser when connecting to the origin
20 // override_host_header: 'example.com',
21
22 // The list of origin hosts to which to connect
23 hosts: [
24 {
25 // The domain name or IP address of the origin serve r
26 location: 'my-custom-property.com',
27 },
28 ],
29
30 // Uncomment the following to configure a shield
31 // shields: { us_east: 'DCD' },
32 },
33 ],
34
35 // Options for hosting serverless functions on Edgio
36 // serverless: {
37 // // Set to true to include all packages listed in the dependencies property of package.json when deploying to Edgio.
38 // // This option generally isn't needed as Edgio automatically includes all modules imported by your code in the bundle that
39 // // is uploaded during deployment
40 // includeNodeModules: true,
41 //
42 // // Include additional paths that are dynamically loaded by your app at runtime here when building the serverless bundle.
43 // include: ['views/**/*'],
44 // },
45
46 // The maximum number of URLs that will be concurrently prerendered during deployment when static prerendering is enabled.
47 // Defaults to 200, which is the maximum allowed value.
48 // prerenderConcurrency: 200,
49
50 // A list of glob patterns identifying which source files should be uploaded when running edgio deploy --includeSources.
51 // This option is primarily used to share source code with Edgio support personnel for the purpose of debugging. If omitted,
52 // edgio deploy --includeSources will result in all files which are not gitignored being uploaded to Edgio.
53 //
54 // sources : [
55 // '**/*', // include all files
56 // '!(**/secrets/**/*)', // except everything in the secrets directory
57 // ],
58};
The relevant configuration options generated include the name and origins properties that will be used later.
  • The name property is used to identify your Edgio property in the Edgio Console
  • The origins property is used to configure the origins to which the router will connect when handling requests.
Learn more about the edgio.config.js file and all the configuration options it supports.

Routes File

The @edgio/core package provides a JavaScript API for controlling routing and caching from your code base rather than a CDN web portal. Using this EdgeJS approach allows this vital routing logic to be properly tested, reviewed, and version controlled, just like the rest of your application code.
Using the router, you can:
  • Proxy requests to upstream sites
  • Send redirects from the network edge
  • Render responses on the server using Next.js and Nuxt.js, or any other framework that supports server side rendering.
  • Alter request and response headers
  • Send synthetic responses
As mentioned above, the routes.[js|ts] file is created during the initialization process.
By default, our CLI automatically creates routes.js and edgio.config.js upon initializing a property (edgio init). If your web application supports TypeScript and it uses a framework for which we have a TypeScript implementation, then our CLI will create routes.ts instead of routes.js.
The routes file contains Rules that:
  • Identifies requests by HTTP method, URL path, query string parameters, cookies, and request headers.
  • Determines how our CDN will handle the above requests. For example, you may configure those requests to be cached, prefetched, passed through without modification, served as static content, and more.

Default Route Configuration

By default, your routes.[js|ts] contains the following configuration:
JavaScript
1// This file was added by edgio init.
2// You should commit this file to source control.
3import {Router, edgioRoutes} from '@edgio/core';
4
5export default new Router()
6 // Here is an example where we cache api/* at the edge but prevent caching in the browser
7 // .match('/api/:path*', {
8 // caching: {
9 // max_age: '1d',
10 // stale_while_revalidate: '1h',
11 // bypass_client_cache: true,
12 // service_worker_max_age: '1d',
13 // },
14 // })
15
16 // plugin enabling basic Edgio functionality
17 .use(edgioRoutes);
The above route matches all requests that start with /api/ and instructs Edgio to:
  • Cache those requests on our network for one day.
  • Allow us to serve stale content for one hour.
  • Instruct the browser to treat the response as immediately stale.
  • Allow prefetched requests to be served from cache for one day.
  • Proxy those requests to your origin backend when we cannot serve them from cache.

Routes

A route identifies a set of requests through any combination of URL path, HTTP method, cookies, request headers, query string parameters and more (see Conditions). The following routes show various ways for identifying requests.

Parts of a Route

Routes define a set of Rules that determine how requests will be handed by Edgio.
In EdgeJS, this is broken down into two parts when calling a router function. We’ll dive deeper into the different available methods below, but for now, will use the .match() method as an example.
The .match() takes two arguments: .match(criteria, features). The .match() API documentation will provide you with the specific type definitions, but we’ll refer to them as criteria and features throughout this guide.
  • criteria can be a String for a simple path matching, or an Object that defines more specific criteria for matching requests such as HTTP method, headers, cookies, and query string parameters.
  • features is an Object that defines how Edgio will handle the requests that match the criteria, such as caching, redirects, proxying to an origin server, and more.

Route Criteria

Below are some simple examples of how to match requests using the .match() method.
  • Match all requests:
    JavaScript
    1router.match('/:path*', {
    2 // features
    3});
  • Match all GET requests whose URL path starts with /marketing/images/:
    JavaScript
    1router.get('/marketing/images/:path*', {
    2 // features
    3});
  • Match all GET and POST requests whose URL path starts with /marketing/images/ and contain the sport request header set to basketball:
    JavaScript
    1router.match(
    2 {
    3 path: '/marketing/images/:path*',
    4 method: /GET|POST/i, // regular expression
    5 headers: {sport: /^basketball$/i}, // keys are header names; values are regular expressions
    6 },
    7 {
    8 // features
    9 }
    10);
Learn more advanced syntax with Route Criteria and Conditions.

Route Features

Once you have identified a set of requests, you need to define how Edgio will handle those requests. The following routes show various ways in which requests can be processed.
  • Apply a caching policy to all requests and proxy cache misses to the origin backend:
JavaScript
1router.match('/:path*', {
2 {
3 caching: {
4 max_age: "1h"
5 },
6 origin: {
7 set_origin: "origin"
8 }
9 }
10 })
  • Set the images response header and proxy cache misses to the origin backend for all GET requests whose URL path starts with /marketing/images/:
JavaScript
1router.get('/marketing/images/:path*', {
2 headers: {
3 set_response_headers: {
4 images: 'true',
5 },
6 },
7 origin: {
8 set_origin: 'origin',
9 },
10});
  • Redirect a URL to its new location:
JavaScript
1router.get('/old/path', {
2 url: {
3 url_redirect: {
4 code: 301,
5 source: '\\/old\\/path',
6 destination: '/new/path',
7 },
8 },
9});
Learn more advanced syntax with Route Features.

Defining Routes

Routes are defined by calling a method on the Router class based on the HTTP method you intend to match. For example, you can handle a GET request a specific path or pattern using the Router.get(...) method. The router contains methods for all the supported HTTP methods. The following methods are available:
  • delete
  • get
  • head
  • match (matches any HTTP method)
  • options
  • patch
  • post
  • put
A full list of supported functions can be found in the Router API documentation.

Route Execution

When Edgio receives a request, it executes each route that matches the request in the order in which they are declared.
Multiple routes can therefore be executed for a given request. A common pattern is to render the response with middleware such as nextRoutes while adding caching for a route that may also be handled by the middleware. In the following example we render a response with Next.js and cache it at the edge for 1 hour:
JavaScript
1import {Router} from '@edgio/core';
2import {nextRoutes} from '@edgio/next';
3
4export default new Router()
5 // Send requests to serverless and render the response with Next.js
6 .use(nextRoutes)
7
8 // Cache all requests to /products/:id for 1 hour
9 .get('/products/:id', {
10 caching: {max_age: {200: '1h'}, stale_while_revalidate: '1h'},
11 });

Testing Locally

You may run Edgio in local development mode to preview your website on your local machine prior to deployment. Local development mode allows for rapid development by letting you to quickly test changes prior to deployment.
  1. From the command line or terminal, type edgio dev.
  2. Preview your website by loading https://127.0.0.1:3000 from within your preferred web browser.

Deploying Your Property

Evaluate site performance and QA functionality by deploying your property to Edgio. Run the following command from your property’s root directory:
Bash
1edgio deploy
Assess performance and caching behavior from the Edgio Console. Fine-tune your configuration by adding routes and then redeploying your property. Once you are ready to serve production traffic through Edgio, update your site’s DNS to point to our service.
Learn more.

Examples

Use our sample website to gain hands-on experience on how to set up Edgio Performance. Specifically, you can browse our sample websites, view their source code, and even experiment on them by deploying them to Edgio.
Simple Example
This example demonstrates a basic Edgio configuration for publicdomainreview.org. It contains two routes that cache content according to their file extension.

Issues?

If you have any issues during this process, check our forums for assistance.