Merik C.
Merik C.

Reputation: 253

Can cloudflare add custom headers?

Is there any way to add custom headers in cloudflare?

We have some https ajax to cache static files, but it's not handling headers like "Access-Control-Allow-Credentials" in response header and cause failure on chrome.

Upvotes: 9

Views: 12922

Answers (2)

Aaron Queenan
Aaron Queenan

Reputation: 921

Scott Helme has published a way to do it using new recently released Cloudflare Workers.

https://scotthelme.co.uk/security-headers-cloudflare-worker/

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",
}

let sanitiseHeaders = {
  "Server": "My New Server Header!!!",
}

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

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

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

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

Upvotes: 11

bobmarksie
bobmarksie

Reputation: 3646

To add custom headers, select Workers in Cloudflare.

CloudFlare Workers

To add custom headers such as Access-Control-Allow-Credentials or X-Frame-Options then add the following little script: -

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

async function handleRequest(request) {
  let response = await fetch(request)
  let newHeaders = new Headers(response.headers)
  newHeaders.set("Access-Control-Allow-Credentials", "true")
  newHeaders.set("X-Frame-Options", "SAMEORIGIN")
  
  // ... and any more required headers

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

Once you have created your worker, you need to match it to a route e.g.

Match route to worker

If you now test your endpoint using e.g. Chrome Dev tools, you will see the response headers.

Upvotes: 6

Related Questions