Is my Function being requested too often (recursing?)

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.

Where are you running this Function? Is it on every single request such as via _middleware.js? If so, this’ll also fire for every asset on your site too.

So for example, if I load your website that requests 2 images, 2 JS files, 2 CSS files, and the HTML file, that’s going to be 7 effective invocations for each page load.

1 Like

I wondered if that might be the case. I’m running it as index.js right now, but there are 7 or 8 GET requests for that page.

Is there a way to only invoke the Function on the initial request, or are those extra runs the tradeoff of using Functions to add my CSP headers?

You might be able to prevent the Function from running on specific requests by using a _routes.json.

1 Like

I follow you. By adding the directories I want ignored to the exclude array in _routes.json, I might be able to reduce the number of Function invocations.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.