Skip to content

Content filters

Content filters are a way to manipulate the response before it is sent to the client.

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

Getting started

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 is manipulated as it is streamed to the client, so you can alter the response in real-time on chunks of data.

Examples

Replacing content in the response

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

class contentFilter extends TransformStream {
constructor(event) {
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();
}
}

Injecting JavaScript into the response

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

class contentFilter extends TransformStream {
constructor(event) {
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();
}
}

Applying a content filter to a route

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).