Skip to main content
Version: 3.4.0

JavaScript for Compute@Edge

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@Edge platform.

If you haven't used Compute@Edge before, start by setting up your first Compute@Edge program over on developer.fastly.com so that you have a working development environment.

To learn more about the fundamentals of using JavaScript with Compute@Edge, 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 Compute@Edge 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.