Skip to content

Content filters

Content filters are a way to manipulate the response before it is sent to the client. This includes both the response body and headers.

This can be useful for a variety of purposes such as:

  • Injecting additional content or scripts into the response
  • Using regex to replace content in the response
  • Blocking access to certain content
  • Implementing security measures, such as preventing markup containing reference to a compromised third-party service
  • Programmatically adding or modifying response headers

To begin, create a new content filter in the QuantCDN dashboard from the “Compute > Content filters” section.

The code editor will open in the right-hand pane. By default, the editor will contain a basic example of a content filter.

The response body is manipulated as it is streamed to the client, so you can alter the response in real-time on chunks of data. Response headers can also be modified before they are sent to the client.

The filter must declare a class named contentFilter that extends TransformStream. Its constructor receives (event, responseHeaders). The body arrives in chunks, so a word split across two chunks is not matched by a simple replace.

A content filter rule continues to the rules below it. If several content filter rules match a request, only the last one applies, so combine filters into one function.

Variables you declare with const, let or function, and the properties of your contentFilter instance, are new for every request. Filters run in strict mode, so assigning to a variable you never declared throws a ReferenceError and does not create a global. Only values you write to the global object explicitly, such as globalThis.memberName = ..., or changes you make to built-in objects such as Array.prototype, can outlive a request.

Where that state can and cannot be seen:

  • It can be seen by later requests that run the same filter for the same project.
  • It is never visible to other projects.
  • It is never visible to your other content filters, edge functions or auth functions.
  • Publishing a new version of the filter starts it with a clean global scope.
  • It is not guaranteed to survive between requests either, because Quant can discard it at any time. Do not use it as a cache.

The following filter greets signed-in members. It keeps the member’s name on globalThis so a helper can read it, which looks harmless when you test it with one browser:

// Unsafe: the name stays on globalThis after this request ends.
function greeting() {
return globalThis.memberName ? `<p>Welcome back, ${globalThis.memberName}</p>` : '';
}
class contentFilter extends TransformStream {
constructor(event, responseHeaders) {
const cookie = event.request.headers.get('cookie') || '';
const match = cookie.match(/member=([^;]+)/);
if (match) globalThis.memberName = decodeURIComponent(match[1]);
const banner = new TextEncoder().encode(greeting());
super({
start(controller) {
controller.enqueue(banner);
},
});
}
}

When a member called Alice loads a page, the filter stores Alice. If the next request to that filter comes from a visitor with no member cookie, nothing overwrites the value, so that visitor can be greeted as Alice. Response headers and cookies stored this way leak in the same way.

Pass the value through local variables instead:

// Safe: the name lives only as long as this request.
function greeting(memberName) {
return memberName ? `<p>Welcome back, ${memberName}</p>` : '';
}
class contentFilter extends TransformStream {
constructor(event, responseHeaders) {
const cookie = event.request.headers.get('cookie') || '';
const match = cookie.match(/member=([^;]+)/);
const memberName = match ? decodeURIComponent(match[1]) : null;
const banner = new TextEncoder().encode(greeting(memberName));
super({
start(controller) {
controller.enqueue(banner);
},
});
}
}

The same applies to anything derived from the request or the response, such as tokens, headers, the client IP address and parts of the page body. If a value has to be shared between functions in your filter, pass it as an argument or keep it on the filter instance.

The following example shows how to replace all instances of the word “example” with the word “test”.

class contentFilter extends TransformStream {
constructor(event, responseHeaders) {
super({
transform: (chunk, controller) => {
const chunkStr = this.textDecoder.decode(chunk);
const transformedChunkStr = chunkStr.replace(/example/g, 'test');
const outputBytes = this.textEncoder.encode(transformedChunkStr)
controller.enqueue(outputBytes);
},
});
this.textEncoder = new TextEncoder();
this.textDecoder = new TextDecoder();
}
}

The following example shows how to inject a custom script into the response, before the closing </body> tag.

class contentFilter extends TransformStream {
constructor(event, responseHeaders) {
const clientCountryCode = event.request.headers.get('client-geo-country') ?? 'XX'
super({
transform: (chunk, controller) => {
const chunkStr = this.textDecoder.decode(chunk);
// Example alert script with the client country code
const exampleScript = `<script>alert('${clientCountryCode}');</script>`
const transformedChunkStr = chunkStr.replace('</body>', exampleScript + '</body>');
const outputBytes = this.textEncoder.encode(transformedChunkStr)
controller.enqueue(outputBytes);
},
});
this.textEncoder = new TextEncoder();
this.textDecoder = new TextDecoder();
}
}

Content filters can also manipulate response headers programmatically. This is powerful for implementing dynamic caching strategies, A/B testing, geo-targeting, or adding context-aware headers based on request characteristics.

class contentFilter extends TransformStream {
constructor(event, responseHeaders) {
const url = new URL(event.request.url);
const userAgent = event.request.headers.get('user-agent') || '';
const clientCountry = event.request.headers.get('client-geo-country') ?? 'XX';
const isMobile = /mobile|android|iphone/i.test(userAgent);
// Dynamic cache control based on device type and path
if (url.pathname.startsWith('/api/')) {
// API endpoints: no caching
responseHeaders.set('cache-control', 'no-store, must-revalidate');
} else if (isMobile) {
// Mobile: shorter cache for frequently changing layouts
responseHeaders.set('cache-control', 'public, max-age=300');
} else {
// Desktop: longer cache
responseHeaders.set('cache-control', 'public, max-age=3600');
}
// Add custom headers for analytics/debugging
responseHeaders.set('x-device-type', isMobile ? 'mobile' : 'desktop');
responseHeaders.set('x-client-country', clientCountry);
// A/B testing: assign variant based on country
const variant = ['US', 'CA', 'GB'].includes(clientCountry) ? 'A' : 'B';
responseHeaders.set('x-ab-variant', variant);
let replacementValue = `Variant ${variant} for ${clientCountry} (${isMobile ? 'mobile' : 'desktop'})`;
let tokenPattern = '{{ PLACEHOLDER_TOKEN }}';
super({
transform: (chunk, controller) => {
const chunkStr = this.textDecoder.decode(chunk);
const transformedChunkStr = chunkStr.replace(tokenPattern, replacementValue);
const outputBytes = this.textEncoder.encode(transformedChunkStr)
controller.enqueue(outputBytes);
},
});
this.textEncoder = new TextEncoder();
this.textDecoder = new TextDecoder();
}
}

To apply a content filter to the route, you can add a new Page Rule to apply to specific domains or routes (or any other supported condition).