NOTE:
@fastly/compute-js-contextis provided as a Fastly Labs product. Visit the Fastly Labs site for terms of use.
@fastly/compute-js-context exposes Fastly Compute resources to your Compute JavaScript application. It provides it as one typed, immutable context object, or as a custom, strongly-typed object mapping your service's specific resource names to their handles.
The core export is createContext, which returns a single, immutable Context object.
type Context = Readonly<{
ACLS: Acls;
BACKENDS: Backends;
CONFIG_STORES: ConfigStores;
ENV: Env;
KV_STORES: KVStores;
LOGGERS: Loggers;
SECRET_STORES: SecretStores;
}>;Each top-level field is a Proxy. Accessing a property lazily looks up and caches the corresponding runtime object. Unknown names return undefined.
- A single source of truth: grab everything off
ctx.* - Typed and safe: TypeScript-first, with
undefinedfor optional resources - Lazy + memoized: nothing is created until accessed
- Readonly: the
Contextis immutable - Customizable: use
buildContextProxyto create a bespoke, typed binding object for your app
Requires a Fastly Compute JavaScript project (
@fastly/js-compute).
npm install @fastly/compute-js-contextThis example shows basic usage of the main Context object.
/// <reference types="@fastly/js-compute" />
import { createContext } from '@fastly/compute-js-context';
addEventListener('fetch', (event) => event.respondWith(handler(event)));
async function handler(event) {
const ctx = createContext();
// Environment - strings, or undefined if not set
console.log('FASTLY_SERVICE_VERSION', ctx.ENV.FASTLY_SERVICE_VERSION);
// Secret Store - property is the SecretStore object, or undefined if not configured
const awsSecrets = ctx.SECRET_STORES.AWS_CREDENTIALS;
const keyId = await awsSecrets?.get('AWS_ACCESS_KEY_ID');
console.log('key id', keyId?.plaintext());
// Backend - pass to fetch() options, or learn about the backend
const origin = ctx.BACKENDS.origin;
const res = await fetch("/", { backend: origin });
// Logger - send output to a named Fastly logging endpoint.
const myLogEndpoint = ctx.LOGGERS.my_log_endpoint;
myLogEndpoint?.log(`${event.request.url} ${event.client.address}`);
return new Response("ok");
}For an even better developer experience, buildContextProxy creates a typed object that maps your application's specific binding names to the underlying Fastly resources. This gives you shorter names and better autocompletion.
First, define your bindings. The key is the name you want to use, and the value is a string identifying the resource type and (optionally) the resource name if it differs from the key.
Then, pass these definitions to buildContextProxy().
/// <reference types="@fastly/js-compute" />
import { buildContextProxy, type BindingsDefs } from '@fastly/compute-js-context';
// Define your application's bindings
const bindingsDefs = {
// Simple mapping: key 'assets' maps to KVStore named 'assets'
assets: 'KVStore',
// Remapping: key 'origin' maps to Backend named 'origin-s3'
origin: 'Backend:origin-s3',
// Explicit mapping for a logger
auditLog: 'Logger:audit_log',
} satisfies BindingsDefs; // <-- for full type safety
// This is the generated type for your bindings object
type Bindings = ContextProxy<typeof bindingsDefs>;
addEventListener('fetch', (event) => event.respondWith(handler(event)));
async function handler(event: FetchEvent): Promise<Response> {
// Create the typed environment
const bindings: Bindings = buildContextProxy(bindingsDefs);
// Now use your custom bindings!
const asset = await bindings.assets?.get('/index.html');
const res = await fetch("/", { backend: bindings.origin });
bindings.auditLog?.log('Request received');
return new Response(asset);
}Creates the main immutable Context. Each sub-object is a Proxy that:
- Resolves lazily on first property access
- Caches the resolved handle for subsequent accesses
- Returns
undefinedfor names that don’t exist - Is not enumerable by design (don’t rely on
Object.keys)
Creates a custom, strongly-typed proxy object based on your definitions.
bindingsDefs: Aconstobject defining your desired bindings- Key: The property name you want on your final
contextProxyobject - Value: A string in the format
'ResourceType'or'ResourceType:actual-name'
- Key: The property name you want on your final
- Returns: A proxy object
contextProxywith your custom bindings. Accessing a property on this object looks up the resource from the mainContext
Defines a type that represents the context proxy, inferred from your bindings definitions.
Extends the passed-in object with a custom, strongly-typed proxy object based on your definitions.
target: An object to extendbindingsDefs: Aconstobject defining your desired bindings- Key: The property name you want on your final
contextProxyobject - Value: A string in the format
'ResourceType'or'ResourceType:actual-name'
- Key: The property name you want on your final
- Returns: A proxy object
contextProxythat extendstargetwith your custom bindings. Accessing a property on this object looks up the resource from the mainContextbefore falling back totarget.
These are the raw shapes available on the main
Contextobject.
ENV:Record<string, string | undefined>, with theFASTLY_*variables (such asFASTLY_SERVICE_VERSION) declared as known keysSECRET_STORES:Readonly<Record<string, SecretStore | undefined>>CONFIG_STORES:Readonly<Record<string, ConfigStore | undefined>>KV_STORES:Readonly<Record<string, KVStore | undefined>>BACKENDS:Readonly<Record<string, Backend | undefined>>LOGGERS:Readonly<Record<string, Logger | undefined>>ACLS:Readonly<Record<string, Acl | undefined>>
- Don’t enumerate category proxies; treat them as name-indexed lookups
- Don’t mutate the context or its sub-objects; it’s intentionally
Readonly - Expect
undefinedfor missing resources and code accordingly (?./guard)
npm install
npm run build # compile src/ to build/
npm test # typecheck + unit tests
npm run test:coverage # unit tests with a coverage report
npm run test:integration # integration tests (requires the Fastly CLI)Unit tests live in test/unit/ and use Node's built-in test runner (node:test) with no extra dependencies. They require Node.js 22.18 or later, which runs the TypeScript sources directly. Since the fastly:* modules only exist inside the Compute runtime, test/unit/hooks.ts (loaded with --import) resolves them to in-memory fakes in test/unit/fakes/. Tests declare which resources exist with provision() from test/unit/fakes/registry.ts; opening anything else throws, as it does in the real runtime.
To run a single file or test:
node --import ./test/unit/hooks.ts --test test/unit/proxy.test.ts
node --import ./test/unit/hooks.ts --test --test-name-pattern='falls back to the target' 'test/unit/**/*.test.ts'Integration tests exercise the packed library inside the real Compute runtime, against each @fastly/js-compute version listed in test/integration/sdk-versions.mjs (the minimum supported 3.x, the latest 3.x, and the latest 4.x, pinned to exact versions):
npm run test:integrationcleans, then builds the library tobuild/.test/integration/build-apps.mjspacks the library withnpm pack. For each SDK version, it copiestest/integration/app/totest/integration/.work/sdk-<version>/, installs the tarball and that exact SDK version there, type-checksapp/type-assertions.tsagainst that SDK's types, and compilesapp/index.jswith that SDK'sjs-computetobin/main.wasm.test/integration/context.test.tsserves each Wasm binary withfastly compute serve(Viceroy), using the local resources declared intest/integration/app/fastly.toml, and checks that each version's JSON report matches the expected values. Viceroy's output is saved to.work/sdk-<version>/serve.log.
These require the Fastly CLI on your PATH, and network access to install each SDK version. Set FASTLY_CLI to use a different binary.
To test other SDK versions, set SDK_VERSIONS to comma-separated versions or ranges:
SDK_VERSIONS="^3,^4" npm run test:integrationAfter a build, the tests can be re-run without rebuilding with node --test test/integration/context.test.ts.
CI runs the unit tests and the integration tests on pull requests and pushes to main, and also runs the integration tests weekly against the latest ^3 and ^4.
If you encounter any non-security-related bug or unexpected behavior, please file an issue using the bug report template.
Please see our SECURITY.md for guidance on reporting security-related issues.
MIT.