JavaScript on the Compute platform

The guidance on this page was tested with an older version (3.30.1) of the JavaScript SDK. It may still work with the latest version (3.33.2), but the change log may help if you encounter any issues.

The Compute platform supports application code written in JavaScript bundled into a WebAssembly (Wasm) binary. It is a great SDK to get started with on the platform if you are used to writing browser-based JavaScript or Node.js applications.

The Compute JavaScript runtime is designed to be compliant with JavaScript standards and the Minimum Common Web APIs (defined by the WinterTC). It uses web platform APIs such as the Streams API and Fetch API, enabling it to interoperate with other modern JavaScript code.

Quick access

HINT: If you are using a JavaScript web framework such as Gatsby, Next.js, or Remix, check out using frameworks on the Compute platform.

Project layout

Development for Fastly Compute in JavaScript involves Node.js for developer tooling and dependency management (Node.js is not involved in the execution of the built Fastly Compute application).

If you don't yet have Node.js and a Compute service set up, start by getting set up.

HINT: For an alternative method to initialize your Compute application with JavaScript or TypeScript, use npm with the @fastly/compute initializer to interactively initialize your application.

$ mkdir example && cd example
$ npm create @fastly/compute@latest

See the @fastly/create-compute initializer's reference page for full options (e.g., if you want to use a directory other than the current one).

At the end of the initialization process, the current working directory will contain a file tree resembling the following:

├── src
│ └── index.js
├── fastly.toml
├── package.json
└── README.md

The most important file to work on is src/index.js, which contains the logic you'll run on incoming requests. If you initialized your project from the default starter kit, the contents of this file should match the one in the starter kit's repository. The other files include:

  • package.json: your project's package metadata, managed using npm, Node's package manager. Includes important information such as the name, module type, and dependencies.
    • We recommend setting "type" to "module", enabling your project to use the modern ES module format.
    • We recommend setting "private" to true, so that the project doesn't accidentally get published as a package.
  • fastly.toml: metadata required by Fastly to deploy your package to a Fastly service. It is generated by the fastly compute init command. Learn more about fastly.toml.

IMPORTANT: Some starter kits may include a webpack configuration or other module bundling tooling. If you are using webpack or similar tools, you may need to include rules to ensure that Fastly's namespaced imports (fastly:*) work correctly. Learn more about module bundling.

Main interface

Incoming requests trigger an event handler function with a fetch event. This may look familiar if you've used the Service Worker API.

A FetchEvent will be dispatched for each request that Fastly receives that's routed to your service, and any associated EventListeners must synchronously call event.respondWith with a valid response to send to the client. The FetchEvent's .request property is a standard web Request, while .client exposes data about the requesting client.

Although event.respondWith must be called synchronously, the argument provided to it may be a Promise, so it is often convenient to define an async function to handle the request and return a promised Response. This pattern is generally the best way to get started writing a Compute program in JavaScript:

src/index.js
JavaScript
3
4
5
6
7
8
9
10
11
12
addEventListener("fetch", event => event.respondWith(handleRequest(event)) );
async function handleRequest(event) {
// Get the request from the client.
const req = event.request;
return fetch(req, {
backend: "example_backend"
});
}

The FetchEvent is provided by the @fastly/js-compute module, Fastly's JavaScript SDK, which is included in your project's dependencies automatically when you run the fastly compute init command.

Communicating with backend servers and the Fastly cache

You can make HTTP requests from your Fastly service by passing a Request to the fetch() function. Our implementation of fetch offers a few extra properties compared to the web standard version, including .backend, which allows you to specify the name of a backend defined statically on your service, or pass an instance of a dynamic backend. If you specify a backend hostname as part of completing the fastly compute deploy wizard, it will be named the same as the hostname or IP address, but with . replaced with _ (e.g., 151_101_129_57). It's a good idea to define backend names as constants:

const backendName = "my_backend_name";

And then reference them when you want to forward a request to a backend:

src/index.js
JavaScript
3
4
5
6
7
8
9
10
11
12
13
14
import { CacheOverride } from "fastly:cache-override";
const backendName = "my_backend_name";
function handler(event) {
// Create a cache override.
let cacheOverride = new CacheOverride({ ttl: 60 });
return fetch(event.request, {
backend: backendName,
cacheOverride
});
}

If using dynamic backends, optionally call allowDynamicBackends() to automatically create backends on demand from the properties of the Request:

/// <reference types="@fastly/js-compute" />
import { Backend } from "fastly:backend";
async function app() {
// For any request, return the fastly homepage -- without defining a backend!
return fetch('https://www.fastly.com/');
}
addEventListener("fetch", event => event.respondWith(app(event)));

HINT: Many JavaScript libraries expect to use the standard fetch API to make HTTP requests. If your application imports a dependency that makes HTTP calls using fetch, those requests will fail unless dynamic backends are enabled on your account.

Requests forwarded to a backend will typically transit the Fastly readthrough cache interface, and the response may come from cache. See Readthrough (HTTP) cache for more precise or explicit control over the Fastly readthrough cache.

Customizing cache behavior

JavaScript SDK: Customizing cache behavior with the readthrough (HTTP) cache is an opt-in feature; enable it by adding the --enable-http-cache flag to the js-compute-runtime command used to build your application (usually the "build" script of package.json):

js-compute-runtime --enable-http-cache ./src/index.js ./bin/main.wasm

The readthrough cache interface can be further customized in the way it interacts with the backend, supporting use cases such as:

  • making modifications to a request only when it is forwarded to a backend
  • reading and modifying response status code and headers, and adjusting cache controls
  • transforming the body of the response that is stored into the cache

See Customizing cache interaction with the backend for details.

HINT: Check out the Advanced caching starter kit for JavaScript, which includes some working examples of this feature and can be used as a starting point for your application.

Composing requests and responses

In addition to the Request referenced by event.request and Response objects returned from the fetch() function, requests and responses can also be constructed. This is useful if you want to make an arbitrary API call that is not derived from the client request, or if you want to make a response to the client without making any backend fetch at all.

To compose a request from scratch, instantiate a new Request:

// Create some headers for the request to origin
let upstreamHeaders = new Headers({ "some-header": "someValue" });
// Create a POST request to our origin using the custom headers
let upstreamRequest = new Request("https://example.com/", {
method: "POST",
headers: upstreamHeaders,
});

Similarly, responses can be created by instantiating a Response:

src/index.js
JavaScript
4
5
6
7
8
9
10
11
const headers = new Headers();
headers.set('Content-Type', 'text/plain');
return new Response("Hi from the edge", {
status: 200,
headers,
url: event.request.url
})

Parsing and transforming responses

Requests and responses in the Compute platform are streams, which allows large payloads to move through your service without buffering or running out of memory. Conversely, running methods such as text on a Response will force the stream to be consumed entirely into memory. This can be appropriate where a response is known to be small or needs to be complete to be parsable.

Parsing JSON responses is available natively in the Fetch API via the json() method of a Response but also requires consuming the entire response into memory:

let backendResponse = await fetch("https://example-backend-host/api/checkAuth", {
method: "POST",
backend: "example_backend",
});
// Take care! .json() will consume the entire body into memory!
let jsonData = await backendResponse.json();
jsonData.newProperty = "additional data";
return new Response(
JSON.stringify(jsonData),
{ headers: { "Content-Type": "application/json" } }
);

However, it is better to avoid buffering responses, especially if the response is large, being delivered slowly in multiple chunks, or capable of being rendered progressively by the client. The Fastly JavaScript SDK implements WHATWG streams. In this example, the backend response is capitalized as it's received, and each chunk is passed on to the client once it has been transformed:

/// <reference types="@fastly/js-compute" />
// Create a transform stream that uppercases text
class UppercaseTransform extends TransformStream {
constructor() {
super({
transform: (chunk, controller) => {
const chunkStr = this.textDecoder.decode(chunk);
const transformedChunkStr = chunkStr.toUpperCase();
const outputBytes = this.textEncoder.encode(transformedChunkStr)
controller.enqueue(outputBytes);
}
});
this.textEncoder = new TextEncoder();
this.textDecoder = new TextDecoder();
}
}
async function handler(event) {
const clientReq = event.request;
clientReq.headers.delete('accept-encoding');
const backendResponse = await fetch(clientReq, { backend: "example_backend" });
// Pass the backend response through a filter, which uppercases all the text.
const newBodyStream = backendResponse.body.pipeThrough(new UppercaseTransform());
// Construct a response using the filtered stream and deliver it to the client.
return new Response(newBodyStream, {
headers: {
...backendResponse.headers,
"cache-control": "private, no-store"
}
});
}
addEventListener("fetch", event => event.respondWith(handler(event)));

Compression

Fastly can compress and decompress content automatically, and it is often easier to use these features than to try to perform compression or decompression within your JavaScript code. Learn more about compression with Fastly.

Using edge data

Fastly allows you to configure various forms of data stores to your services, both for dynamic configuration and for storing data at the edge. The JavaScript SDK exposes the fastly:config-store and fastly:kv-store packages to allow access to these APIs.

All edge data resources are account-level, service-linked resources, allowing a single store to be accessed from multiple Fastly services.

Environment variables

Compute services can access a set of defined environment variables provided by the system at runtime as well as custom environment variables you specify at build-time. See environment variables for the Compute platform for details.

Logging

console provides a standardized interface for emitting log messages to STDOUT or STDERR.

To send logs to Fastly real-time logging, which can be attached to many third-party logging providers, use the Logger class. Log endpoints are referenced in your code by name:

/// <reference types="@fastly/js-compute" />
import { Logger } from "fastly:logger";
function handler(event) {
// logs "Hello!" to the "JavaScriptLog" log endpoint
const logger = new Logger("JavaScriptLog");
logger.log("Hello!");
return new Response({ status: 200 });
}
addEventListener("fetch", event => event.respondWith(handler(event)));

If your code errors, output will be emitted to stderr:

// This logs "abort: Oh no! in src/index.js(line:col)" to stderr.
throw new Error('Oh no!');

Using dependencies

The Compute JavaScript SDK is designed to follow Node.js behavior for handling packages and supports the installation of dependency packages using the npm install command.

A JavaScript application for Compute must include Fastly's public package @fastly/js-compute as a dependency as it includes the JavaScript runtime enabling the application to execute within and interact with the Fastly platform.

An application may depend on additional packages obtained through the npm repository or any other compatible channel. The Compute JavaScript platform supports WinterTC-compatible npm modules, which in practice are modules that don't depend on any specific platform's bindings at runtime (outside Fastly Compute).

Our Fiddle tool allows the use of an approved subset of modules for experimentation that we have tested and confirmed will work with the Compute platform:

This is a tiny fraction of the modules which will work on the Compute platform, but these are the most commonly useful modules when building applications.

Developer experience

For the best experience of developing for the Compute platform in JavaScript, include the following comment at the top of any file that works with Fastly objects or fastly: namespaced modules:

/// <reference types="@fastly/js-compute" />

This will allow your IDE to import the type definitions for the Fastly JavaScript SDK. If you use eslint with a custom eslintrc file, you may also need to add some extensions to recognize the Fastly types:

{
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
]
}

Usage with TypeScript

TypeScript is a popular programming language that extends JavaScript to add syntax for types. With some modification to the setup of your application, it's possible to use TypeScript source files with Compute.

HINT: The quickest way to get set up with TypeScript is by using the TypeScript starter kit.

To add TypeScript to an existing JavaScript project, you can set up the tsc TypeScript compiler to compile your TypeScript files during each build by following these steps:

NOTE: The following steps assume that your source files are in the src subdirectory.

  1. Add typescript to your project's devDependencies.

    npm install --save-dev typescript
  2. Add a tsconfig.json file to the root of your project with the following content, which is the recommended starting point. For information about the properties that can be set in this file, see the tsconfig.json documentation.

    {
    "compilerOptions": {
    "strict": true,
    "rootDir": "src",
    "outDir": "build",
    "allowJs": true,
    "module": "ES2022",
    "lib": [ "ES2022" ],
    "moduleResolution": "bundler",
    "customConditions": [ "fastly" ],
    "esModuleInterop": true
    }
    }
  3. Add the following prebuild script and update the build script in your package.json file. This will compile your TypeScript files to JavaScript during each build and use that output as the source of your Compute program.

    {
    "scripts": {
    "prebuild": "tsc",
    "build": "js-compute-runtime build/index.js bin/main.wasm"
    }
    }
  4. Because this setup compiles your TypeScript source files to a temporary subdirectory build during the build process, add this directory to your .gitignore file:

    /build
  5. Rename your index.js file to index.ts. Type:

    mv src/index.js src/index.ts
  6. Now, build your project as usual. You'll need to add any necessary type annotations. For example, add the FetchEvent type to the event object in your handler.

    async function handler(event: FetchEvent) {
    // ...
    }

Module bundling

Compute applications written in JavaScript that have the standard structure and standard dependencies can be built using the tools included with the JavaScript SDK. However, if your application needs to perform advanced tasks at build time, such as replacing global modules, providing polyfills, or transforming code (such as JSX, TypeScript, or JavaScript syntax proposals), you can use a module bundler.

WARNING: Using a module bundler may cause the resulting bundle - and therefore the compiled Wasm package - to become significantly larger. Compute packages are subject to platform and account-level limits on the maximum package size.

Typically, the module bundler is added to a Compute application project as a dependency and run in a prebuild script, configured to place its output in an intermediate location. The build script is also modified to use those intermediate files as its input. Note that the specific configuration will vary depending on your application's needs and the bundler.

The Fastly Compute JavaScript SDK makes some of its features available through fastly: namespaced imports, such as fastly:env. In order to use these imports with a bundler, you may need to add configuration so that it recognizes these as platform imports rather than modules that exist in node_modules.

The following are some bundlers that have been seen to work with Fastly Compute along with some recommended configuration options.

Using webpack

When using webpack as a bundler with Fastly Compute, use the following recommended values in its webpack.config.js configuration file at minimum:

  • target - Set to false, as the predefined targets provided by webpack do not match the Compute platform.
  • devtool - Set to false, as incremental builds do not make sense in the context of Compute.
  • output.filename - The name of the intermediate file. Use a file with the .cjs extension.
  • output.chunkFormat - Set to 'commonjs'.
  • output.library.type - Set to 'commonjs'.
    • The output format supported by webpack is the older CommonJS module (ES module output by webpack is still experimental and not fully supported). During the bundling process, code is transformed to CommonJS syntax (e.g., import and export are converted to require() and module.exports =). Create the bundled output file with a .cjs extension, so that the file is treated as a CommonJS module regardless of the "type" value of the package.
  • externals - Set to [/^fastly:.*$/]. Indicates to webpack that fastly: imports should be looked up as platform imports rather than modules under node_modules.
  • resolve.extensions - Set to [].
  • resolve.conditionNames - Set to ['fastly', '...']. Indicates to webpack to load the appropriate variant of packages that offer packages that recognize the fastly platform. The value '...' indicates to webpack to insert the default list of conditions here.
    • If you're using react-dom, use ['fastly', 'edge-light', '...'].

Using these as a starting point, you can further customize the configuration to meet your needs. For example:

HINT: A great way to get up and running with webpack for bundling a Compute application is by using the Compute starter kit for webpack, which comes complete with a starting point webpack.config.js file.

Using esbuild

When using esbuild as a bundler with Fastly Compute, it's recommended to use the JavaScript API to run esbuild. Use the following recommended configuration values at minimum:

  • bundle - Set to true. Tells esbuild to run in bundle mode, in other words, to inline the dependency modules into the output file.
  • platform - Set to 'neutral' - Tells esbuild to use neutral defaults.
  • external - Set to ['fastly:*']. Indicates to esbuild that fastly: imports should be looked up as platform imports rather than modules under node_modules.
  • conditions - Set to ['fastly'].
    • If you're using react-dom, use ['fastly', 'edge-light'].

Using these as a starting point, you can further customize the configuration to meet your needs. For example:

  • loader - can be used to determine how input files will be treated.
  • alias - can be used to replace modules at build time.
  • plugins - can be used to include plugins, which are modules that can inject code at various points in time during bundling.
  • Refer to the esbuild Build options for more details.

HINT: A great way to get up and running with esbuild for bundling a Compute application is by using the Compute starter kit for esbuild, which comes complete with a starting point configuration file.

Testing and debugging

Logging is the main mechanism to debug Compute programs. Log output from live services can be monitored via live log tailing. The local test server and Fastly Fiddle display log output automatically. See Testing & debugging for more information about choosing an environment in which to test your program.

Most common logging requirements involve HTTP requests and responses. It's important to do this in a way that doesn't affect the main program logic, since consuming a response body can only be done once. The following example demonstrates a console.log statement for request headers, response headers, request body and response body:

Since the bodies of HTTP requests and responses in Compute programs are streams, we are consuming the stream using the convenience .text() method and then logging the resulting data. In JavaScript once the .body property of a request or response has been read it cannot be used by fetch or respondWith, so we use the extracted body data to construct a new Request or Response after logging the body.

WARNING: Logging body streams in this way will likely slow down your program, and may trigger a memory limit if the payload is large.

Unit testing

You may choose to write unit tests for small independent pieces of your JavaScript code intended for the Compute platform. However, Compute programs heavily depend on and interact with Fastly features and your own systems. This can make an integration testing strategy that focuses on a lesser number of high impact tests more valuable.

HINT: You can use @fastly/compute-testing to write tests from Node.js, against a local or remote Fastly Compute application.