Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
let securityHeaders = {
"Content-Security-Policy": "default-src 'self' 'unsafe-inline'",
"X-Xss-Protection": "1; mode=block",
"X-Frame-Options": "DENY",
"Referrer-Policy": "strict-origin-when-cross-origin",
"Permissions-Policy": "accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()"
};
addEventListener('fetch', event => {
event.respondWith(addHeaders(event.request));
});
async function addHeaders(req) {
let response = await fetch(req);
if (404 === response.status) {
return new Response(null, {
status: 307,
statusText: "Temporary Redirect",
headers: { "Location": "/404/" }
});
}
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]);
});
let reqUrl = new URL(req.url);
if ("/404/" === reqUrl.pathname) {
return new Response(response.body, {
status: 404,
statusText: "Not Found",
headers: newHdrs
});
}
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHdrs
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment