Hello community,
I’m using a Pages Function to create a Content-Security Policy with nonces for inline scripts. Things are working as expected, but each time I invoke the Function, it adds 7-8 to my Functions count for the day. I wonder if I’m invoking it too often or there’s a recursion happening I don’t need.
// Additional code for HTMLRewriter and nonce generator omitted for brevity
export const onRequest = async ({ request, next, env }) => {
const response = await next();
if (response.status === 304) {
return response;
} else {
response.headers.set(
"Content-Security-Policy",
"default-src 'self'; ... et al"
);
response.headers.set("cf-nonce-generator", "HIT");
// Find the nonce string and replace it
const rewriter = new HTMLRewriter()
.on("script", new AttributeWriter("nonce", oldValue, newValue))
.transform(response);
return rewriter;
}
};
My only thought is to switch onRequestGet
to onRequest
because this Function should only be invoked on GET requests. Other than that I have no good ideas and haven’t found any documentation to optimize number of invocations.