Please help me troubleshoot this Worker code

So I found on an online blog here:

https://scotthelme.co.uk/csp-nonces-the-easy-way-with-cloudflare-workers/

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:

SEE UPDATED CODE BELOW

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 => {
	event.respondWith(addHeaders(event.request))
})

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": [
        "'self'",
        ],
        "script-src": [            
            "app.ecwid.com",
            "*cloudfront.net",
            "'nonce'",
        ],
    }

    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) {
                directives.push(directive)
            } 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!

:frowning:

Don’t know how I missed your post. Apologies. First try fixing only one piece of the puzzle - use .cloudfront.net instead of cloudfront.net. Or better yet the exact cloudfront domains. Note that you may have to simply use cloudfront.net 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.