Please help me troubleshoot this Worker code

So I found on an online blog here:

code for adding crypto nonces via Workers, and would love to implement it, but when I try to use the code, I am getting the following error and was hoping someone could shed some insight:


Please see the UPDATED CODE BELOW.

I have now updated my code to the following code, which no longer throws any errors when saving the worker, but it is causing my webpage to error out with a 500 status code? Any idea why?

    addEventListener('fetch', event => {

async function addHeaders(req) {
    let cspNonce = btoa(crypto.getRandomValues(new Uint32Array(2)))

    let newReq = new Request(req)
    newReq.headers.set(CSP-NONCE, cspNonce)
    let response = await fetch(newReq)

    const cspConfig = {
        "default-src": [
        "script-src": [            

    function buildCspHeader(cspConfig, nonce = null) {
        let directives = []

        Object.keys(cspConfig).forEach(function(directive) {
            let values = Array.from(cspConfig[directive])
            values.forEach(function(value, key) {
                if (nonce && value === "'nonce'") {
                    values[key] = "'nonce-" + nonce + "'"
                } else if (nonce === null && value === "'nonce'") {
                    values.splice(key, 1)
            if (values.length === 0) {
            } else {
                directives.push(directive + ' ' + values.join(' '))

        return directives.join('; ')

    let newResponseHeaders = response.headers
    newResponseHeaders.set('Content-Security-Policy', buildCspHeader(cspConfig, cspNonce))
    let init = {
        headers: newResponseHeaders,
        status: response.status,
        statusText: response.statusText

    return new Response(response.body, init)


Anyone see what might be causing my page not to load with the above code? Would be greatly appreciated! Thanks!


Don’t know how I missed your post. Apologies. First try fixing only one piece of the puzzle - use instead of Or better yet the exact cloudfront domains. Note that you may have to simply use without the wildcard prefix, which would not be ideal, from a security standpoint. Using the exact source domains would be best, from a security standpoint.