'Can cloudflare add custom headers?
Is there anyway to add custom headers in cloudflare?
We hvae 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.
Solution 1:[1]
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
})
}
Solution 2:[2]
To add custom headers, select Workers
in Cloudflare.
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.
If you now test your endpoint using e.g. Chrome Dev tools, you will see the response headers.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Aaron Queenan |
Solution 2 | bobmarksie |