I was bothered by the result under the security section (score)
on sites like these https://www.webpagetest.org/ & https://securityheaders.com/
however with Cloudflare workers it is very easy to solve this problem
The example below is for those who know what they are doing and how to customize the code to fit their website - I am not responsible !
Cloudflare offers a free plan which contains

- go to CF and select the workers section from the top menu
- Create a worker
- name it here
4.1 copy/paste this code (modify if necessary)
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
})
async function handleRequest(request) {
const response = await fetch(request);
return getSecuredResponse(response);
}
const securityHeaderMap = {
"Strict-Transport-Security" : "max-age=2592000; includeSubDomains; preload",
"Content-Security-Policy" : "upgrade-insecure-requests",
"Feature-Policy" : "accelerometer 'none'; camera 'none'; geolocation 'none'; gyroscope 'none'; magnetometer 'none'; microphone 'none'; payment 'none'; usb 'none'",
"Referrer-Policy" : "strict-origin-when-cross-origin",
"X-Content-Type-Options" : "nosniff",
"X-Frame-Options" : "SAMEORIGIN",
"X-Xss-Protection" : "1; mode=block"
};
const headerDeletionList = [
"X-Powered-By"
];
async function getSecuredResponse(response) {
let responseHeaders = new Headers(response.headers);
// Return immediately if response is not 'text/html'
if(isResponseContentTypeNotHtml(responseHeaders)) {
return response;
}
// Add security headers to response.
Object.entries(securityHeaderMap).map(([name, value]) => responseHeaders.set(name, value));
// Delete headers from response.
headerDeletionList.forEach(name => responseHeaders.delete(name));
// Return response with modified headers.
return new Response(response.body , {
status: response.status,
statusText: response.statusText,
headers: responseHeaders
});
}
function isResponseContentTypeNotHtml(headers) {
const contentType = headers.get('content-type');
return !contentType || !contentType.includes("text/html");
}
4.2 save
- now it is necessary to tell the worker when it will be activated (add route)
select the workers tab again from the top menu
6.1 domain or all subdomains, etc… - consult here (click me)
6.2 the name of our worker
6.3 I chose not to throw out the error
8. if it doesn’t work properly - edit the trigger or worker code
Good luck !
useful link OWASP Secure Headers Project | OWASP Foundation