Edgio makes it easy to develop, test, and deploy serverless functions without a JavaScript framework. Simply declare your routes and use the
compute
function or proxy
with the transformResponse
option to compute responses based on your own custom logic.Prerequisites
Setup requires:
- An Edgio account. Sign up for free.
- An Edgio property. Learn how to create a property.
- Node.js. View supported versions and installation steps.
- Edgio CLI.
Install the Edgio CLI
If you have not already done so, install the Edgio CLI.
Bash
1npm i -g @layer0/cli@latest
Getting Started
To create a new Edgio project using serverless functions, run:
Bash
1npx @layer0/cli@latest init
Or you can clone this example repo: layer0-serverless-example, which has some more complex examples of how to use serverless functions:
Bash
1npx degit https://github.com/layer0-docs/layer0-serverless-example my-serverless-functions
Responding to requests
Use the compute function to generate a synthetic response:
JavaScript
1// routes.js2import { Router } from '@layer0/core'34export default new Router().get('/some-route/:someParam', ({ compute }) => {5 compute((req, res) => {6 // Here you can access the following information about the request:7 // ================================================================89 // To get the request path and query string10 const url = req.url // e.g /some/path?foo=bar1112 // To get the request body as a string13 const body = req.body1415 // To get the request method:16 const method = req.method1718 // To get the headers sent from the browser:19 const headers = req.getHeaders() // keys are always lower-case2021 // To get the value of a specific request header:22 const someHeader = req.getHeader('some-header') // the header name is case-insensitive2324 // To check if https was used25 const isHttps = req.secure2627 // To access query parameters28 const { id, name } = req.query // for example if the query string is ?id=1&name=Mark2930 // To access path parameters:31 const { someParam } = req.params3233 // To specify the response:34 // ================================================================3536 // To set a response header:37 res.setHeader('content-type', 'application/json')3839 // To set the response body, use:40 res.body = 'some string'4142 // To set the response status:43 res.statusCode = 20044 res.statusMessage = 'OK'45 })46})
See ResponseWriter for all of the functions that you can call when responding to a request.
Modifying a response from the origin
Serverless functions can be used to modify responses from the origin by using the
proxy
function with the transformResponse
option. First, configure an origin by adding a backend
to layer0.config.js
in the root of your project:JavaScript
1// layer0.config.js2module.exports = {3 backends: {4 origin: {5 // The domain name or IP address for the origin server6 domainOrIp: 'origin.example.com',78 // Optionally set a host header for Edgio to send when connecting to the origin.9 // If omitted, the host header will be forwarded from the browser.10 hostHeader: 'origin.example.com',11 },12 },13}
See backends for more configuration options.
To forward a request to the origin and modify the response using a serverless function:
JavaScript
1// routes.js2import { Router } from '@layer0/core'34export default new Router().get('/some-route/:someParam', ({ proxy }) => {5 proxy('origin', {6 transformRequest: req => {7 // You can optionally transform the request before it is sent to the origin8 // Here you can modify the following information about the request:9 // ================================================================1011 // To alter the request URL:12 req.url = '/some/path?foo=bar'1314 // To alter the request body:15 req.body = JSON.stringify({ foo: 'bar' })1617 // To alter the request method:18 req.method = 'POST'1920 // To get the headers sent from the browser:21 const headers = req.getHeaders()2223 // To get the value of an incoming request header:24 const someHeader = req.getHeader('some-header') // the header name is case-insensitive2526 // To set a request header:27 req.setHeader('content-type', 'application/json') // the header name is case-insensitive2829 // To remove a request header:30 req.removeHeader('some-header') // the header name is case-insensitive3132 // To access query parameters33 const { id, name } = req.query // for example if the query string is ?id=1&name=Mark3435 // To access path parameters:36 const { someParam } = req.params37 },38 transformResponse: (res, req) => {39 // To access or modify the body, use:40 res.body = 'some string'4142 // To set a header:43 res.setHeader('content-type', 'application/json') // the header name is case-insensitive4445 // To remove a header:46 res.removeHeader('some-header') // the header name is case-insensitive4748 // To get the headers returned from the origin. Keys are always lower case49 const headers = res.getHeaders()5051 // To get a specific header returned from the origin:52 const cookie = res.getHeader('cookie') // the header name is case-insensitive53 },54 })55})
You can also access any of the request fields documented in Responding to requests.
Caching Responses
To improve performance and minimize cost, cache the responses returned by your serverless functions whenever possible:
JavaScript
1// routes.js2import { Router } from '@layer0/core'34export default new Router().get('/', ({ cache, compute }) => {5 cache({6 edge: {7 maxAgeSeconds: 60 * 60, // cache for one hour at the edge8 staleWhileRevalidateSeconds: 60 * 60 * 24, // and continue to serve stale responses for up to 24 hours while fetching a fresh response9 },10 })11 compute((req, res) => {12 res.setHeader('content-type', 'application/json')13 res.body = JSON.stringify({ message: 'Hello World!' })14 })15})
See the cache function for more options.
Running your project locally
Test your app with the Sites on your local machine by running the following command in your project’s root directory:
Bash
10 dev
This will start your project in watch mode. Any changes your make to your source code will instantly take effect without restarting.
Deploying your project to Edgio
Deploy your app to the Sites by running the following command in your project’s root directory:
Bash
10 deploy
Limits
Edgio serverless functions have a maximum runtime of 20 seconds per request. If a function exceeds this limit, Edgio will respond with a 539 status.
See Limits for more information.