Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #172.
In order to protect our code from XSS attacks, we can add a cryptographically-generated, random string (i.e., a nonce) to each
<script nonce="...here...">
. Thisnonce
will get recreated by the server on every reload of the page, so only scripts we send from the server can be executed (i.e., the browser will refuse to execute any others, like those injected maliciously).Making this work in Remix wasn't obvious, and requires a few things:
nonce
on every load, and pass it down to all the routes viares.locals
nonce
via helmetjs, which uses theres.locals
to access the value we already generated.res.locals.nonce
value via agetLoaderContext
function we pass tocreateRequestHandler()
, see https://remix.run/docs/en/v1/route/loader#contextroot
needs to define aloader()
function, which accepts thecontext
arg. This includes thenonce
value.Document
component callsuseLoaderData()
to access thenonce
and passes it as aprop
to all the various "script" components, see https://remix.run/docs/en/v1/file-conventions/rootIn summary: we generate a
nonce
in Express, use it in helmetjs to define our CSP headers, then pass it through to Remix to render the script tags in the browser using the nonce.To test this, try loading the page with the console open, and watch for any CSP issues.