Adds features to the route using features json object. This can be used to combine functional style route setting with object style route setting.
This RouteHelper method should be called as first RouteHelper method in the same rule to ensure that other methods such as serveStatic are not partially overridden by specified features.
Example
import { Router } from '@edgio/core/router'
export default new Router()
.get('/images/:files*', ({ addFeatures, serveStatic }) => {
addFeatures({
response: {
optimize_images: true,
}
})
serveStatic('images/:files*')
})
Adds a set-cookie
header to the response.
This does not replace any cookies with the same name - for that you should use updateResponseCookie
.
Example
new Router()
.get('/some/path', ({ addResponseCookie, proxy }) => {
proxy('origin')
addResponseCookie('my-cookie', 'my-cookie-value', { domain: 'test.com' })
})
Name of the cookie to add.
Value to set
Optional
options: defaultOptional options to add to cookie
Adds new response header without replacing existing headers with the same name before delivering the response downstream.
Example
new Router()
.get('/some/path', ({ addResponseHeader, proxy }) => {
proxy('origin')
addResponseHeader('some-header', 'some-value')
})
The case-insensitive name of the response header
The value to set
Sends the necessary response headers to allow CORS.
Example
new Router()
.match('/api/:path*', ({ allowCors }) => {
allowCors({
origin: '*', // this is the default
methods: ['get', 'post'],
headers: ['x-some-header'],
maxAge: 60 * 60, // one hour
credentials: true
})
})
Serves an HTML app shell from a static file with HTML content-type. This method can be used to serve the initial HTML for a single page app.
The path to the app shell html file
Example
new Router()
.fallback(({ appShell }) => {
appShell('dist/index.html')
})
Sets the caching behavior for both browser and edge.
The cache()
method can be called in the same rule where the proxy()
is called or in any other rule that matches the same path.
Example
import { Router } from '@edgio/core/router'
export default new Router()
.get('/p/:productId', ({ cache, proxy }) => {
cache({
browser: {
maxAgeSeconds: 0,
serviceWorkerSeconds: 60 * 60, // 1 hour
},
edge: {
maxAgeSeconds: 60 * 60 * 24, // 24 hours
staleWhileRevalidateSeconds: 60 * 60 // 1 hour
}
})
proxy('origin')
})
Registers a new Edgio Cloud Function. The provided callback function is executed in Edgio's serverless cloud. The callback is passed the request and the response
Use this method when you need to compute a response in the cloud rather than at the edge or at build time. A common example is when the response must be computed based on request parameters, headers, or cookies.
A common example is to look up the destination for a redirect from an external API:
new Router()
.get('/products/:id', ({ redirect, compute }) => {
compute(async (request, response) => {
const destination = await getDestinationFromAPI(request.params.id)
response.statusCode = 302
response.setHeader("Location", destination)
})
})
This method can be combined with cache
to compute complex responses in the cloud and cache them at edge:
new Router()
.get('/products/:id', ({ cache, compute }) => {
cache({
edge: {
maxAgeSeconds: 60 * 60 * 24,
}
})
compute(async (request, response) => {
const product = await getProductFromAPI(request.params.id)
response.setHeader("content-type", "application/json")
response.body = JSON.stringify({
success: true,
product,
})
})
})
Note: Extracted params from express-style criteria are available as object under req.params. When regular expression is used as path criteria, the matched group params are available as array under req.params.$. Example: $1 => req.params.$[1]
A function to run in the cloud to compute the response
Allows to enable/disable the Edgio Image Optimizer for the matched path. The optimizer is disabled by default.
The optimizer can be configured using query search params in request URL or request headers.
See https://docs.edg.io/guides/v7/performance/image_optimization for more details.
Example
new Router()
.get('/images/:path*', ({ optimizeImages }) => {
optimizeImages(true)
})
Relays the request to the specified origin.
Example
new Router()
.get('/some/path/with/:variable', ({ proxy }) => {
proxy('legacy', { path: '/some/other/path/with/:variable' })
})
In this example, we relay the request to the "legacy" origin. In this case, edgio.config.js
must
contain a definition for the legacy
origin. For example:
// edgio.config.js
module.exports = {
routes: "./routes.js",
...
origins: [
{
name: 'legacy',
balancer: 'round_robin',
hosts: [{ location: 'legacy.domain.com' }],
},
],
}
NOTE: The proxy is executed at the edge unless the transformRequest
or transformResponse
options are provided.
In that case, the proxy is executed using Edgio Cloud Functions.
Example of transformResponse
import { Router } from '@edgio/core/router'
import responseBodyToString from '@edgio/core/utils/responseBodyToString';
new Router()
.get('/some/path/with/:variable', ({ proxy }) => {
proxy('legacy', {
transformResponse: async (res) => {
// Simple headers manipulation
res.setHeader('x-custom-header', 'custom-value')
}
})
})
.get('/another/path/with/:variable', ({ proxy }) => {
proxy('legacy', {
transformResponse: async (res) => {
// Body can be encoded by brotli, gzip, deflate or plain text. We need to decode it first.
const originalBody = responseBodyToString(res.body)
// Remove content-encoding header as we are changing the body
res.removeHeader('content-encoding')
// Modify the body
res.body = originalBody.replace('</body>', '<script src="https://example.com/script.js"></script></body>')
}
})
})
NOTE: When both res.body and res.chunks are present with different values in transformResponse, the res.body will be preferred over the chunks and used as the final response.
The name of one of the origins in your edgio.config.js
file.
Optional
options: ProxyOptionsRedirects the browser to a new location. Query params from the original request are added to the redirect URL. Complex redirects manipulating query string are computed using Edgio Cloud Functions.
Examples
new Router()
.get('/p/:productId', ({ redirect }) => {
return redirect('/products/:productId', { statusCode: 301 })
})
.
// The substitution group params can be used in the redirect location when path criteria is Regular Expression.
new Router()
.get(//p/(.+)/, ({ redirect }) => {
return redirect('/products/$1', { statusCode: 301 })
})
// Extract id from route and apply as query string
new Router()
.get('/p/:productId', ({ redirect }) => {
return redirect('/product', { query: { id: ':productId' }})
})
new Router()
.get(//p/(\d+)/?/, ({ redirect }) => {
return redirect('/product', { query: { id: '$1' }})
})
// Extract id from query string and apply to route
new Router()
.get({ path: '/p', query: { id: ':id' } }, ({ redirect }) => {
return redirect('/product/:id')
})
The URL to which the browser will be redirected.
Removes a response header immediately before delivering the response downstream.
Example
new Router()
.get('/some/path', ({ removeResponseHeader, proxy }) => {
proxy('origin')
removeResponseHeader('some-header')
})
The case-insensitive name of the response header
Removes a header from the response provided by an origin server.
Example
new Router()
.get('/some/path', ({ removeUpstreamResponseHeader, proxy }) => {
proxy('origin')
removeUpstreamResponseHeader('some-header')
})
The case-insensitive name of the response header
Sends string content back to client. If content is a string, the response will be sent directly from the edge. If it is a function, the request will be computed in Edgio's serverless cloud. StatusCode defaults to 200. On error routes we send the status code as null, since we need to preserve the status code of the failed request unless it is provided.
The content to send to the browser
The HTTP status code.
Responds with a static asset from the specified path.
Example
serveStatic('path/to/asset/from/app/root')
You can also use variables in the asset path. For example, to return files under the assets
directory
when the url starts with /static
:
new Router()
.get('/static/:path*', ({ serveStatic }) => {
serveStatic('assets/:path*')
})
The substitution group params can be used in the asset path when path criteria is Regular Expression. The same functionality can be achieved using the code below.
new Router()
.get(//static/(.*)/, ({ serveStatic }) => {
serveStatic('assets/$1')
})
The relative path to the asset from the app's root directory. You can reference path variables using :variable
.
The different options to serving static assets
Serves a service worker with proper edge and browser cache headers.
Optional
filePath: stringThe path to the service worker relative to the root directory of your app
Example
import { Router } from '@edgio/core/router'
export default new Router()
.get('/service-worker.js', ({ serviceWorker }) => {
serviceWorker('dist/service-worker.js')
})
Allows to set a comment feature on the rule, which will be displayed in the dashboard. The comment message supports markdown.
The comment message.
If true, the comment will be appended to the existing comment.
Allows to change the origin that the request is proxied to. This is useful when you want to proxy to a different origin based on the matched rule. The origin set by the latest matched rule will be used.
Example
new Router()
.get('/:path*', ({ setOrigin }) => {
setOrigin('fallback_origin')
})
.get('/products/1', ({ setOrigin }) => {
setOrigin('web_origin')
})
The origin name
Adds or replaces a request header.
Example
new Router()
.get('/some/path', ({ setRequestHeader, proxy }) => {
setRequestHeader('some-header', 'some-value')
proxy('origin')
})
The case-insensitive name of the request header
The value to set
Adds or replaces a response body. It optionally sets response code or message.
new Router()
.get('/some/path', ({ setResponseBody }) => {
setResponseBody('<html><body>Hello World!</body></html>', 200, 'OK')
})
The response body.
Optional
code: HttpStatusCodeThe response code.
Optional
done: booleanIndicates that this is last feature
Adds or replaces a response code.
new Router()
.get('/some/path', ({ setResponseCode, proxy }) => {
setResponseCode(200)
proxy('origin')
})
The response code.
Adds or replaces existing response header
immediately before delivering the response downstream.
New value can be appended to the end of existing value by prepending a +
symbol to the header name.
Example
new Router()
.get('/some/path', ({ setResponseHeader, proxy }) => {
proxy('origin')
setResponseHeader('new-header', 'some-value')
setResponseHeader('+existing-header', 'other-value')
})
The case-insensitive name of the response header
The value to set
Allows to easily configure common security headers in single method call. For example: X-Frame-Options, X-XSS-Protection, X-Content-Type-Options. The security headers are pre-configured with default values that should suit most applications.
By default, all security headers are added with default values, and you can disable single headers by setting their value to false or override the default value by setting the value to a string.
HINT: If you wish to configure HSTS header, you can do so in Router.forceHttps()
method.
Example
new Router()
// Forces HTTPS for all paths and sets HSTS header
.forceHttps()
// Sets security headers with default values to all paths
.get('/:path*', ({ setSecurityHeaders }) => {
addSecurityHeaders()
})
// Customize security headers for specific paths
.get('/products/:path*', ({ setSecurityHeaders }) => {
addSecurityHeaders({
xFrameOptions: false,
referrerPolicy: 'no-referrer'
})
})
Rewrites the request path.
Example:
router.get('/products/:id', ({ updatePath }) => {
updatePath('/p/:id')
})
The substitution group params can be used in the asset path when path criteria is Regular Expression. The same functionality can be achieved using the code below.
new Router()
.get(//products/(.+)/, ({ updatePath }) => {
updatePath('/p/$1')
})
a new route path, which can include params captured from the original path
Alters a request header. Use this method to derive the new header value from the existing one.
Example
new Router()
.get('/some/path', ({ updateRequestHeader, proxy }) => {
updateRequestHeader('some-header', /some-.*-part/gi, 'some-replacement')
proxy('origin')
})
The case-insensitive name of the request header
Regex to find the part that should be replaced.
Value that will replace the matched part.
Alters a response header immediately before delivering the response downstream. Use this method to derive the new header value from the existing one.
Example
new Router()
.get('/some/path', ({ updateResponseHeader, proxy }) => {
proxy('origin')
updateResponseHeader('some-header', /some-.*-part/gi, 'some-replacement')
})
The case-insensitive name of the response header
Regex to find the part that should be replaced.
Value that will replace the matched part.
Generated using TypeDoc
RouteHelper makes it easy to implement common request handling patterns and provides backwards compatibility with Layer0's ResponseWriter class. Please pay attention to the following notes when using RouteHelper to avoid unexpected behavior.
Retrieving the RouteHelper instance
When a function is passed to the second argument of a rule, that function is provided with an instance of RouteHelper as the sole argument.
Example:
Overriding methods
The below RouteHelper methods are partially or fully overriding each other and should not be used together in the same rule. Only the method in the last matched rule will be performed.
Example:
Incorrect usage of methods
All RouteHelper methods are independent by design and cannot be nested or called from each other.
Example of incorrect usage: