JavaScript for Fastly Compute
This site is the full SDK reference for @fastly/js-compute
, the module that provides the interface between your JavaScript code and the Fastly Compute platform.
If you haven't used Fastly Compute before, start by setting up your first Fastly Compute program over on developer.fastly.com so that you have a working development environment.
To learn more about the fundamentals of using JavaScript with Fastly Compute, see our using JavaScript guide.
Understanding the JavaScript SDK
Incoming HTTP requests to domains that are attached to your Fastly service will start an instance of your application and invoke a fetch
event, which can be bound using the addEventListener
function:
addEventListener("fetch", event => event.respondWith(handleRequest(event)) );
async function handleRequest(event) {
const req = event.request;
return fetch(req, {
backend: "example_backend"
});
}
Fastly specific features are available as named imports from fastly:
prefixed modules, all of which are documented in this site. For example, the env function provides access to environment variables and can be imported into your application like this:
import { env } from "fastly:env"
JavaScript code compiled for Fastly Compute has access to a global environment with most of the globals you would expect in an ECMAScript runtime, like Date
and console
.
Trying things out
Fastly fiddle is an online web-based playground where you can run Fastly code. You'll see fiddles included in many pages of our developer hub and this SDK reference. These interactive examples can be executed right on the page by clicking the RUN tab:
/// <reference types="@fastly/js-compute" />
async function app(event) {
const request = event.request;
return new Response(`You made a request to ${request.url}`)
}
addEventListener("fetch", event => {
event.respondWith(app(event));
});
Check out fiddle.fastly.dev
to create your own.