The @layer0/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, Nuxt.js, Angular, or any other framework that supports server side rendering.
When Edgio receives a request, it executes each route that matches the request in the order in which they are declared until one sends a response. The following methods return a response:
Multiple routes can therefore be executed for a given request. A common pattern is to add caching with one route and render the response with a later one using middleware. In the following example we cache then render a response with Next.js:
JavaScript
1const{Router}=require('@layer0/core/router')
2const{ nextRoutes }=require('@layer0/next')
3
4// In this example a request to /products/1 will be cached by the first route, then served by the `nextRoutes` middleware
You can inject values from the request or response into headers or cookies as template literals using the ${value} format. For example: setResponseHeader('original-request-path', '${path}') would add an original-request-path response header whose value is the request path.
Value
Embedded value
Description
HTTP method
${method}
The value of the HTTP method used for the request (e.g. GET)
URL
${url}
The complete URL path including any query strings (e.g. /search?query=docs). Protocol, hostname, and port are not included.
Path
${path}
The URL path excluding any query strings (e.g. /search)
Query string
${query:<name>}
The value of the <name> query string or empty if not available.
Request header
${req:<name>}
The value of the <name> request header or empty if not available.
Request cookie
${req:cookie:<name>}
The value of the <name> cookie in cookie request header or empty if not available.
Request named parameter
${req:param:<name>}
The value of the <name> param defined in the route or empty if not available.
Response header
${res:<name>}
The value of the <name> response header or empty if not available.
It is possible to write an unnamed parameter that only consists of a regexp. It works the same the named parameter, except it will be numerically indexed:
You can also match HTTP POST requests based on their request body content as in the following example:
JavaScript
1router.match(
2{
3body:{parse:'json',criteria:{operationName:'GetProducts'}},// the body content will parsed as JSON and the parsed JSON matched against the presence of the criteria properties (in this case a GraphQL operation named 'GetProducts')
4},
5()=>{},
6)
Currently the only body content supported is JSON. Body content is parsed as JSON and is matched against the presence of the fields specified in the criteria field. The POST Body Matching Criteria section below contains examples of using the criteria field.
Body matching can be combined with other match parameters such as headers and cookies. For example,
JavaScript
1router.match(
2{
3// Only matches GetProducts operations to the /graphql endpoint
When body matching is combined with cache in a route, the HTTP request body will automatically be used as the cache key. For example, the code below will cache GraphQL GetProducts queries using the entire request body as the cache key:
9staleWhileRevalidateSeconds:60*60*24,// this way stale items can still be prefetched
10},
11})
12},
13)
You can still add additional parameters to the cache key using the normal EdgeJS key property. For example, the code below will cache GraphQL GetProducts queries separately for each user based on their userID cookie and the HTTP body of the request.
2/* Handle the POST for the GetProducts query specifically */
3})
Note that when the graphqlOperation function is used, the HTTP request body will automatically be included in the cache key.
The graphqlOperation function is provided to simplify matching of common GraphQL scenarios. For complex GraphQL matching (such as authenticated data), you can use the generic Body Matching for POST requests feature.
If you need to block all search engine bot traffic to specific environments (such as your default or staging environment), the easiest way is to include the x-robots-tag header with the same directives you would otherwise set in a meta tag.
To block search engine traffic for Edgio edge links and permalinks, you can use the built-in .noIndexPermalink() call on the router:
JavaScript
1router.noIndexPermalink()
This will match requests with the host header matching /layer0.link|layer0-perma.link/ and set a response header of x-robots-tag: noindex.
Additionally, you can customize this to block traffic to development or staging websites based on the host header of the request:
This example shows typical usage of @layer0/core, including serving a service worker, next.js routes (vanity and conventional routes), and falling back to a legacy backend.
JavaScript./routes.js
1const{Router}=require('@layer0/core/router')
2
3module.exports=newRouter()
4// adds `x-robots-tag: noindex` response header to Edgio
5// edge links and permalinks to prevent bot indexing
6.noIndexPermalink()
7.get('/service-worker.js',({ serviceWorker })=>{
8// serve the service worker built by webpack
9serviceWorker('dist/service-worker.js')
10})
11.get('/p/:productId',({ cache })=>{
12// cache products for one hour at edge and using the service worker
13cache({
14edge:{
15maxAgeSeconds:60*60,
16staleWhileRevalidateSeconds:60*60,
17},
18browser:{
19maxAgeSeconds:0,
20serviceWorkerSeconds:60*60,
21},
22})
23proxy('origin')
24})
25.fallback(({ proxy })=>{
26// serve all unmatched URLs from the origin backend configured in layer0.config.js
You can use the router’s catch method to return specific content when the request results in an error status (For example, a status code of 537). Using catch, you can also alter the statusCode and response on the edge before issuing a response to the user.
The .catch method allows the edge router to render a response based on the result preceeding routes. So in the example above whenever we receive a 5xx, we respond with customized-error-page.html from the application’s root directory, and change the status code to 502.
Your catch callback is provided a ResponseWriter instance. You can use any ResponseWriter method except proxy inside .catch.
We highly recommend keeping catch routes simple. Serve responses using serveStatic instead of send to minimize the size of the edge bundle.
In addition to sending redirects at the edge within the router configuration, this can also be configured at the environment level within the Edgio Developer Console.
Under <Your Environment> → Configuration, click Edit to draft a new configuration. Scroll down to the Redirects section:
Click Add A Redirect to configure the path or host you wish to redirect to:
Note: you will need to activate and redeploy your site for this change to take effect.