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:

 import { Router } from '@edgio/core/router'

export default new Router()
.get('/favicon.ico', ({ serveStatic }) => { // the parameter provided here is an instance of RouteHelper
serveStatic('images/favicon.ico')
})

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.

 RouteHelper.proxy
RouteHelper.compute
RouteHelper.renderWithApp
RouteHelper.serveStatic
RouteHelper.redirect
RouteHelper.setOrigin
RouteHelper.appShell
RouteHelper.send
RouteHelper.setResponseBody
RouteHelper.serviceWorker

Example:

 import { Router } from '@edgio/core/router'

export default new Router()
// This compute() will be executed on all paths except the '/page'.
.get('/:path*', ({ compute }) => {
compute(async (req, res) => {
res.setHeader('content-type', 'text/html')
res.body = '<html><body>Hello World</body></html>'
})
})
// On a '/page' path, the proxy() call will override the compute() above, and just the proxy will be executed.
.get('/page', ({ proxy }) => {
proxy("origin")
})

Incorrect usage of methods

All RouteHelper methods are independent by design and cannot be nested or called from each other.

Example of incorrect usage:

 import { Router } from '@edgio/core/router'

export default new Router()
// This rule will not work!
.get('/page1', ({ compute, cache }) => {
compute(async (req, res) => {
res.body = '<html><body>Hello World</body></html>'
cache({
edge: {
maxAgeSeconds: 60 * 60 * 24,
}
})
})
})
// This rule will work
.get('/page2', ({ compute, cache }) => {
compute(async (req, res) => {
res.body = '<html><body>Hello World</body></html>'
})
cache({
edge: {
maxAgeSeconds: 60 * 60 * 24,
}
})
})

Hierarchy

  • default

Methods

  • 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*')
    })

    Parameters

    Returns void

  • 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' })
    })

    Parameters

    • name: string

      Name of the cookie to add.

    • value: string

      Value to set

    • Optional options: default

      Optional options to add to cookie

    Returns void

  • 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')
    })

    Parameters

    • name: string

      The case-insensitive name of the response header

    • value: string

      The value to set

    Returns void

  • 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
    })
    })

    Parameters

    Returns void

  • 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.

    Parameters

    • indexHtmlPath: string

      The path to the app shell html file

      Example

       new Router()
      .fallback(({ appShell }) => {
      appShell('dist/index.html')
      })

    Returns void

  • 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')
    })

    Parameters

    Returns void

  • 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]

    Parameters

    • fn: ComputeFn

      A function to run in the cloud to compute the response

    Returns void

  • 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)
    })

    Parameters

    • value: boolean = true

    Returns void

  • 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.

    Parameters

    • backend: string

      The name of one of the origins in your edgio.config.js file.

    • Optional options: ProxyOptions

    Returns void

  • Redirects 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')
    })

    Parameters

    • to: string

      The URL to which the browser will be redirected.

    • options: RedirectOptions = {}

    Returns void

  • Removes a request header.

    Example

     new Router()
    .get('/some/path', async ({ removeRequestHeader, proxy }) => {
    removeRequestHeader('some-header')
    proxy('origin')
    })

    Parameters

    • name: string

      The case-insensitive name of the request header

    Returns void

  • Removes a response header immediately before delivering the response downstream.

    Example

     new Router()
    .get('/some/path', ({ removeResponseHeader, proxy }) => {
    proxy('origin')
    removeResponseHeader('some-header')
    })

    Parameters

    • name: string

      The case-insensitive name of the response header

    Returns void

  • Removes a header from the response provided by an origin server.

    Example

     new Router()
    .get('/some/path', ({ removeUpstreamResponseHeader, proxy }) => {
    proxy('origin')
    removeUpstreamResponseHeader('some-header')
    })

    Parameters

    • name: string

      The case-insensitive name of the response header

    Returns void

  • Renders a result in Edgio's serverless cloud using your application. Use this method to respond with an SSR or API result from your application. This method will only work with applications that has serverless backend such as Next.js, Nuxt.js, Express etc...

    Returns void

  • 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.

    Parameters

    • content: string | (() => string)

      The content to send to the browser

    • statusCode: undefined | HttpStatusCode

      The HTTP status code.

    Returns void

  • 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')
    })

    Parameters

    • path: string

      The relative path to the asset from the app's root directory. You can reference path variables using :variable.

    • options: ServeStaticOptions = {}

      The different options to serving static assets

    Returns void

  • Serves a service worker with proper edge and browser cache headers.

    Parameters

    • Optional filePath: string

      The 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')
      })

    Returns void

  • Allows to set a comment feature on the rule, which will be displayed in the dashboard. The comment message supports markdown.

    Parameters

    • message: string

      The comment message.

    • append: boolean = false

      If true, the comment will be appended to the existing comment.

    Returns void

  • 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')
    })

    Parameters

    • name: string

      The origin name

    Returns void

  • Adds or replaces a request header.

    Example

     new Router()
    .get('/some/path', ({ setRequestHeader, proxy }) => {
    setRequestHeader('some-header', 'some-value')
    proxy('origin')
    })

    Parameters

    • name: string

      The case-insensitive name of the request header

    • value: string

      The value to set

    Returns void

  • 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')
    })

    Parameters

    • body: string

      The response body.

    • Optional code: HttpStatusCode

      The response code.

    • Optional done: boolean

      Indicates that this is last feature

    Returns void

  • Adds or replaces a response code.

     new Router()
    .get('/some/path', ({ setResponseCode, proxy }) => {
    setResponseCode(200)
    proxy('origin')
    })

    Parameters

    Returns void

  • 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')
    })

    Parameters

    • name: string

      The case-insensitive name of the response header

    • value: string

      The value to set

    Returns void

  • 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'
    })
    })

    Parameters

    • options: default = {}

    Returns void

  • 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')
    })

    Parameters

    • destination: string

      a new route path, which can include params captured from the original path

    Returns void

  • 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')
    })

    Parameters

    • name: string

      The case-insensitive name of the request header

    • match: RegExp

      Regex to find the part that should be replaced.

    • replace: string

      Value that will replace the matched part.

    Returns void

  • 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')
    })

    Parameters

    • name: string

      The case-insensitive name of the response header

    • match: RegExp

      Regex to find the part that should be replaced.

    • replace: string

      Value that will replace the matched part.

    Returns void

Generated using TypeDoc