# Security Headers Cloudflare Worker

URL: https://sohaib.com/blog/security-headers-cloudflare-worker
Author: Sohaib Khan
Published: Jan 2, 2020
Updated: Nov 27, 2025
Category: Cloud & Infrastructure

> Hardening your headers and secure your site - Special Thanks to pascalandy Goto Worker's and then Launch Editor copy the code - Once done add route and link to your script let securityHeaders = {…

Hardening your headers and secure your site - Special Thanks to [pascalandy](https://gist.github.com/pascalandy/9c2ae76555655af35fc18ddc20e51afd)

Goto Worker's and then Launch Editor copy the code - Once done add route and link to your script

![Article illustration](/uploads/imported/security-headers-cloudflare-worker/01-b8fc60c7-ed11-4b37-bbfa-bd993faec9fe.webp)

![Article illustration](/uploads/imported/security-headers-cloudflare-worker/02-dbb3dafc-8c94-41f0-abf3-2213a3137342.webp)

```javascript
let securityHeaders = {
	"Content-Security-Policy" : "upgrade-insecure-requests",
	"Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload",
	"X-Xss-Protection" : "1; mode=block",
	"X-Frame-Options" : "DENY",
	"X-Content-Type-Options" : "nosniff",
	"Referrer-Policy" : "strict-origin-when-cross-origin",
	"Feature-Policy" : "accelerometer 'none' ; ambient-light-sensor 'none' ; autoplay 'self' ; camera 'none' ; encrypted-media 'none' ; fullscreen 'self' ; geolocation 'none' ; gyroscope 'none' ; magnetometer 'none' ; microphone 'none' ; midi 'none' ; payment 'self' ; picture-in-picture * ; speaker 'self' ; sync-xhr 'none' ; usb 'none' ; notifications 'self' ; vibrate 'self' ; push 'self' ; vr 'none'",	
	"Cache-Control" : "public, max-age=0, must-revalidate",
	"Content-Type" : "text/html; charset=UTF-8",
}

let sanitiseHeaders = {
	"Server" : "headers override",
}

let removeHeaders = [
	"Public-Key-Pins",
	"X-Powered-By",
	"X-AspNet-Version",
]

addEventListener('fetch', event => {
	event.respondWith(addHeaders(event.request))
})

async function addHeaders(req) {
	let response = await fetch(req)
	let newHdrs = new Headers(response.headers)

	if (newHdrs.has("Content-Type") && !newHdrs.get("Content-Type").includes("text/html")) {
        return new Response(response.body , {
            status: response.status,
            statusText: response.statusText,
            headers: newHdrs
        })
	}

	Object.keys(securityHeaders).map(function(name, index) {
		newHdrs.set(name, securityHeaders);
	})

	Object.keys(sanitiseHeaders).map(function(name, index) {
		newHdrs.set(name, sanitiseHeaders);
	})

	removeHeaders.forEach(function(name){
		newHdrs.delete(name)
	})

	return new Response(response.body , {
		status: response.status,
		statusText: response.statusText,
		headers: newHdrs
	})
}
```

You can check your headers right away by going to [https://securityheaders.com/](https://securityheaders.com/)
