Skip to content

Configure Scramjet

xmb9 edited this page Nov 14, 2026 · 2 revisions

Configure Scramjet

You can configure Scramjet in four categories:

  1. Bootstrap options: only if you use @mercuryworkshop/proxy-bootstrap. They control which files are served and which transport is used.
  2. Controller config: where the files live, the URL prefix, and how URLs are encoded.
  3. Scramjet config: rewriter and runtime behavior (flags, per-site flags).
  4. Plugins and hooks: per-frame behavior such as caching, link handling, and request interception.

Bootstrap options

Pass these to bootstrap() on the server. They're also sent to the client, where initBootstrap() uses them.

const { routeRequest, routeUpgrade } = await bootstrap({
	transport: "libcurl",
	swPath: "/sw.js",
});
Option Default Description
transport "libcurl" "libcurl" or "epoxy". ("bare" isn't implemented yet. Epoxy isn't served by routeRequest yet; see Limitations.)
swPath /sw.js URL of the generated service worker
wispPath /wisp/ Path the client transport connects to (the server always listens on /wisp/)
bootstrapInitPath /bootstrap-init.js URL of the script that defines initBootstrap()
scramjetBundlePath /scram/scramjet.js Scramjet core bundle
scramjetWasmPath /scram/scramjet.wasm Rewriter WASM
scramjetUtilsBundlePath /scram/scramjet-utils.js Utils bundle (defines $scramjetUtils)
scramjetControllerApiPath /controller/controller.api.js Controller page bundle (defines $scramjetController)
scramjetControllerInjectPath /controller/controller.inject.js Script injected into proxied pages
scramjetControllerSwPath /controller/controller.sw.js Controller service worker script
libcurlClientPath /clients/libcurl-client.js libcurl transport bundle
epoxyClientPath /clients/epoxy-client.js Epoxy transport bundle

Controller config

These settings control where the controller finds Scramjet's files and how proxied URLs look. Pass them as config when you create the controller:

const controller = new Controller({
	serviceworker,
	transport,
	config: {
		prefix: "/~/sj/",
		scramjetPath: "/scramjet/scramjet.js",
	},
});

You can also change the module-level defaults before you create a controller. This is what proxy-bootstrap does:

const { Controller, config } = $scramjetController;
config.scramjetPath = "/assets/scramjet.js";
Option Default Description
prefix /~/sj/ URL path prefix for proxied content. The full prefix is <prefix><controllerId>/<frameId>/. Your service worker's scope must cover it.
scramjetPath /scramjet/scramjet.js URL of the Scramjet core bundle, injected into every proxied page and worker
wasmPath /scramjet/scramjet.wasm URL of the rewriter WASM
injectPath /controller/controller.inject.js URL of the controller's inject script
virtualWasmPath scramjet.wasm.js Virtual file (relative to the frame prefix) that delivers the WASM to proxied pages. You normally don't need to change this.
codec encodeURIComponent / decodeURIComponent { encode(url), decode(url) }: how the real URL is encoded into the proxied path

Custom codecs

The codec turns https://example.com/page into the part of the proxy URL after the prefix. A URL-safe base64 codec, for example, makes proxied URLs less obvious:

config: {
	codec: {
		encode: (url) => (url ? btoa(url).replace(/\//g, "_").replace(/\+/g, "-") : url),
		decode: (url) => (url ? atob(url.replace(/_/g, "/").replace(/-/g, "+")) : url),
	},
},

Important

The codec functions are converted to strings with Function.prototype.toString() and inserted into every proxied page and worker. They have to be self-contained: no imports, no outside variables, nothing the bundler might rename. Use only built-ins such as btoa, encodeURIComponent, and String.


Scramjet config

scramjetConfig controls the rewriter and the runtime inside proxied pages. Your value is deep-merged on top of the defaults, so you only need to include the keys you change.

import { defaultConfigDev } from "@mercuryworkshop/scramjet";

const controller = new Controller({
	serviceworker,
	transport,
	scramjetConfig: {
		flags: { syncxhr: true },
		siteFlags: {
			"^https://(www\\.)?example\\.com/": { allowInvalidJs: false },
		},
	},
});

@mercuryworkshop/scramjet also exports defaultConfig and defaultConfigDev. defaultConfigDev turns on extra debugging (captureErrors, debugTrampolines, debugSourceURL) and turns off allowInvalidJs. The demo uses it.

Flags

Flag Default Description
syncxhr false Support synchronous XMLHttpRequest. When off, sync XHRs are ignored and a warning is logged.
allowInvalidJs true If a script can't be parsed, serve it unmodified instead of throwing.
allowFailedIntercepts false Ignore errors thrown inside Scramjet's API intercepts instead of passing them to the page. It also enables a faster path without error detection.
sourcemaps true Track rewrites so that Function.prototype.toString() and stack traces show the original source.
destructureRewrites true Rewrite destructuring patterns (e.g. const { location } = window) so they can't leak the real globals.
disableComputedWrap false Don't wrap computed member access (obj[key]). Faster, but less complete.
encapsulateWorkers true Load the rewritten worker code as its own script with a sourceURL, instead of concatenating it into one file.
captureErrors false Catch and log errors in rewritten code (debugging).
cleanErrors false Remove Scramjet internals from error stack traces.
debugTrampolines false Extra checks and logging around intercept trampolines (debugging).
debugSourceURL false Add a //# sourceURL=<original url> comment to rewritten JS so DevTools shows real file names.
rewriterLogs false Log rewriter timing and details.
scramitize false Developer-only rewriter instrumentation.

Per-site flags

siteFlags maps regex (regular expression) strings to partial flag objects. Each key is tested against the full URL (href). If a key matches and its object sets the flag being checked, that value is used. Otherwise the global value applies.

siteFlags: {
	"^https://docs\\.google\\.com/": { syncxhr: true },
	"\\.example\\.org/legacy/": { allowInvalidJs: true, sourcemaps: false },
}

Keys are passed to new RegExp(), so escape . and / as needed.

Other keys

  • maskedfiles: file names hidden from stack traces and performance entries. The controller already adds inject.js and scramjet.wasm.js.
  • globals: names of the internal global functions the rewriter emits ($scramjet$wrap, etc.). Don't change these unless you're also rebuilding the inject scripts.

Plugins

Plugins are passed per frame when you create it:

const frame = controller.createFrame(iframe, {
	plugins: [new HttpCachePlugin(), new UrlWatcherPlugin(console.log)],
});

Built-in plugins (@mercuryworkshop/scramjet-utils)

These come from the npm package, or from the $scramjetUtils global when you use the bootstrap.

Plugin Constructor What it does
HttpCachePlugin new HttpCachePlugin({ cacheName? }) Service worker fetches skip the browser's HTTP cache, so this plugin adds a private HTTP cache that follows RFC 9111, using the Cache API. It stores responses before they're rewritten, so a cached response can be used by any frame.
UrlWatcherPlugin new UrlWatcherPlugin((url) => {...}) Calls your callback whenever the top-level URL changes, including pushState, replaceState, and hash changes. Useful for an address bar.
CatchEscapedLinksPlugin new CatchEscapedLinksPlugin((url) => newLocation) Catches top-level navigations that would leave the proxy, such as "open in new tab" or window.open, and redirects them to the URL your callback returns.
EventHandlerPlugin new EventHandlerPlugin() Lets you add listeners that run after the page's own listeners, even if the page calls stopPropagation.
LinkHandlerPlugin new LinkHandlerPlugin((url) => {...}) Sends link clicks and middle-clicks to your callback, for example to open them in a new tab in your UI. Requires EventHandlerPlugin on the same frame.

A plugin's dependencies must be in the same plugins array, or createFrame throws.

Writing a plugin

Extend ManagedPlugin and register callbacks on the frame's hooks with this.tap():

import { ManagedPlugin } from "@mercuryworkshop/scramjet-controller";
import { ScramjetHeaders } from "@mercuryworkshop/scramjet";

class BlockAdsPlugin extends ManagedPlugin {
	constructor() {
		super("block-ads", []); // name, dependencies (other plugin names)
	}

	install(frame) {
		super.install(frame);

		// Return a response without going to the network
		this.tap(frame.hooks.fetch.intercept, (context, props) => {
			if (context.parsed.url.hostname.endsWith("doubleclick.net")) {
				props.response = {
					body: "",
					status: 204,
					statusText: "No Content",
					headers: ScramjetHeaders.fromRawHeaders([]),
				};
			}
		});

		// Runs in every proxied window once Scramjet has hooked it
		this.tap(frame.hooks.init.post, ({ window, client, isTopLevel }) => {
			if (isTopLevel) console.log("loaded", client.url.href);
		});
	}
}

this.tap(hook, callback, { before?, after? }) accepts a third argument that sets the order relative to other plugins by name. For example, CatchEscapedLinksPlugin runs { after: ["scramjet-http-cache"] }.

Available hooks

Hook When it runs Useful props
frame.hooks.fetch.intercept Before a request is sent Set props.response to answer the request yourself
frame.hooks.fetch.request Just before the transport request Change props.url and props.init, or set props.earlyResponse
frame.hooks.fetch.preresponse Raw upstream response, before rewriting Change or replace props.response
frame.hooks.fetch.response Final rewritten response Change or replace props.response
frame.hooks.init.pre / init.post Before and after Scramjet hooks a proxied window context.window, context.client, context.isTopLevel
frame.hooks.error.request A request handler threw Set props.setResponse to show your own error page, or props.suppressError to stop the console log

Here is an example that uses frame.hooks.error.request to add a custom error page:

this.tap(frame.hooks.error.request, (context, props) => {
	props.suppressError = true;
	props.setResponse = {
		status: 502,
		statusText: "Bad Gateway",
		headers: [["Content-Type", "text/html"]],
		body: `<h1>Couldn't load ${context.rawrequest.rawUrl}</h1><pre>${context.error}</pre>`,
	};
});

Transports

The transport is the object that actually makes network requests. It's passed when you create the controller and can be replaced at any time:

import EpoxyClient from "@mercuryworkshop/epoxy-transport";

controller.setTransport(new EpoxyClient({ wisp: "wss://wisp.example.com/" }));
Transport Package Notes
libcurl @mercuryworkshop/libcurl-transport Default. libcurl compiled to WASM, with TLS done on the client.
Epoxy @mercuryworkshop/epoxy-transport A Rust/WASM TLS client over Wisp.

Both take { wisp: "<ws(s) url>" }. Any object that implements the ProxyTransport interface from @mercuryworkshop/proxy-transports works.

Wisp server options

If you host Wisp with @mercuryworkshop/wisp-js (as proxy-bootstrap does), you can configure it on the server:

import { server as wisp } from "@mercuryworkshop/wisp-js/server";

wisp.options.allow_private_ips = false;
wisp.options.allow_loopback_ips = false;

For a list of options, refer to wisp-js - Changing Server Settings

The Scramjet dev server sets both of these to true so it can proxy localhost. Allowing private or loopback IPs lets proxy users reach services on your server's internal network. Only turn these on for local development.