Skip to content

Looking for a method to inject a custom <script> tag into the head of any HTML response with relevant CSP hash or nonce #8427

@chrskerr

Description

@chrskerr

Describe the problem

We are using newrelic and are exploring their browser timing scripts feature to get access to additional client-side metrics.

This script includes a number of environment specific variables and we are using CSP, so there are a few approaches we can take:

  1. Add the script to app.html, which will allow inserting the csp_nonce but doesn't allow us to access custom env variables for deploy specific api keys, etc, so we can't do deploy specific scripts.
  2. Insert the script via Svelte in +layout.svelte. Pass the script textContent to the browser via load data and insert it into the DOM there. We also calculate the sha hash of the script and manually insert it into the csp header for the request in hooks.server.ts (this is what we are doing now)

I'd like to improve our flow since it feels pretty hacky to me right now

Describe the proposed solution

Proposals:

  1. An ability to access other server env variables in app.html, eg %sveltekit.env.{variableName}%
  2. An ability to access the csp nonce within hooks.server.ts, eg event.nonce. This would allow the script tag to be manually inserted into the html response and to include the nonce in the tag.

Alternatives considered

We are very open to suggestions for different ways to solve this problem :)

Importance

nice to have

Additional Information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions