Security headers are a part of HTTP headers used by web applications to configure security defenses in web browsers. The most commonly used HTTP security headers are Permissions-Policy, X-Frame-Options, Strict-Transport-Security, X-Content-Type-Options, Content-Security-Policy, and Referrer-Policy.

With Cloudflare Workers you can easily return new response to the browser with desired changes. You can write workers functions in Javascript to archive this.

In this tutorial, you learn how to add worker security headers to Cloudflare workers from the dashboard.

Step 1: Create a Cloudflare Workers

Log in to Cloudflare and on the Home page click Workers.

Cloudflare home page

Choose the Workers tab and Click Create a Worker button.

create worker

Step 2: Add the Security header Script

Once you have given a name for the Worker, you can add the script. You need to alter derivative values based on your requirement.

Use the following Worker for Security Headers.

let securityHeaders = {
  "Content-Security-Policy" : "upgrade-insecure-requests",
  "Strict-Transport-Security" : "max-age=1000",
  "X-Xss-Protection" : "1; mode=block",
  "X-Frame-Options" : "DENY",
  "X-Content-Type-Options" : "nosniff",
  "Referrer-Policy" : "strict-origin-when-cross-origin",
  "permissions-policy": "microphone=()",

let sanitiseHeaders = {
  "Server" : "Cloudflare",

let removeHeaders = [

addEventListener('fetch', event => {

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[name]);

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


  return new Response(response.body , {
    status: response.status,
    statusText: response.statusText,
    headers: newHdrs
Worker for Security Headers

Step 3: Assign Route for the worker

Navigate the Cloudflare menu and choose Workers.

Cloudflare home menu

Now run your Worker by assigning it to the routes. You can use the asterisk (*) to create dynamic patterns to match multiple URLs for example **, https://**. Then choose the Worker created before from the drop-down menu.

add worker route

Cloudflare Workers is free for personal use and simple applications.


In this tutorial, we learned how to add worker security headers to Cloudflare workers from the dashboard. Thanks for reading, please provide your feedback and suggestions in the below comment section.