Skip to content

Instantly share code, notes, and snippets.

@randomdross
Created May 13, 2019 22:03
Show Gist options
  • Save randomdross/43e14f4a98c3e46bc93327d1347009d2 to your computer and use it in GitHub Desktop.
Save randomdross/43e14f4a98c3e46bc93327d1347009d2 to your computer and use it in GitHub Desktop.
Cloudflare CSP Worker
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Fetch a request and return the response, with CSP applied
* @param {Request} request
*/
async function handleRequest(request) {
randomNonce = generateNonce(20)
request = new Request(request)
request.headers.set('x-random-csp-nonce', randomNonce)
let response = await fetch(request)
response = new Response(response.body, response)
response.headers.set('Content-Security-Policy', 'object-src \'none\'; script-src \'nonce-' + randomNonce + '\' \'unsafe-inline\' \'unsafe-eval\' \'strict-dynamic\' https: http:; base-uri \'none\';')
return response
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment