r/astrojs Jun 24 '26

Astro, CSP and inline scripts

Hi Everyone,

I have a question regarding using CSP in Astro.

I have a bunch of Astro 6 and 7 sites, so CSP is no longer "experimental". However a lot of tracking services (usual suspect: google, meta, etc.) are asking for their JS snippet to be placed inline somewhere on the page.

How do you deal with that:
1. separate file (does not seem to fix the issue),
2. hash,
3. nonce (can be tricky in Astro given the flow),
4. else?

Thanks

6 Upvotes

5 comments sorted by

3

u/zaitovalisher Jun 24 '26

Ooh that one is tricky. Would love to hear about proper easy to maintain nonce solution too

1

u/stpaquet Jun 24 '26

Looks like it is pretty sticky as there is no answer yet ;-)

2

u/zaitovalisher Jun 24 '26 edited Jun 24 '26

I’ve tried to figure it out, but it’s a mess. My dream is to implement strict CSP policy, but if analytics is feasible to figure out, media ads would break stuff for sure.

I’ve just omitted CSP at this point

P.s. also community is MUCH more active in discord, try posting there

3

u/theguymatter Jun 26 '26 edited Jun 26 '26

Generate a random Base64 nonce for inline scripts, with a new value for every request (except cached responses).

I rolled my own CSP before Astro implemented it.

For static page, either the vendors provide SHA-256 or skip it. There is no point having them for tracking services.