Overview
You can use this document to learn how to modify the request's response body before the response reaches the user's browsers. Specifically, this document displays how to change the background of the response to #000000 by using regex to find and replace the <body> tag.
Before you begin, you must enable serverless scripting for your stack. To learn more, see Enable Serverless Scripting and Create a Script.
View a sample script
In the following example, the route is: modify-response
Review the following sample script:
addEventListener("fetch", event => {
event.respondWith(fetchAndModify(event.request));
})
async function fetchAndModify(request) {
// Send the request on to the origin server.
const response = await fetch(request);
let contentType = response.headers.get('content-type');
if (!contentType || !contentType.startsWith("text/")) {
return response;
}
// Read response body.
const text = await response.text();
// Modify it.
const modified = text.replace(
/^<body.*>$/gm,
'<body style="background: #000000; color: #ffffff">'
);
return new Response(modified, {
status: response.status,
statusText: response.statusText,
headers: response.headers
});
}
Access your script
You can access your script with any of the delivery domains on your account.
Based on the above example, you can access the script with: https://sitehash.stackpathcdn.com/modify-response