DEV Community

Cover image for How I fixed this Next.js error: Refused to load the script because it violate Content Security Policy directive
Ramu Narasinga
Ramu Narasinga

Posted on

How I fixed this Next.js error: Refused to load the script because it violate Content Security Policy directive

Recently, I migrated my portfolio website: to Next.js using template and wanted to integrate Microsoft clarity with Next.js.

At first, I directly copied the script and pasted it in the head tag in layout.tsx and got the following error:

I overlooked the fact that this error is related to Content Security Policy and thought this has to do with me not using Script from Next.js, so I followed along with the steps provided in How to setup Google Analytics and Microsoft Clarity with Nextjs.

I particularly liked the metrics folder structure since this way you could add more external analytics integrations into your app. This medium article uses Script tag. I add these changes and refresh my dev server only to find this error still exists.

Never assume an error without looking at the error message, re-read the error message completely before you make assumptions.

Error message:

Refused to load the script ‘' because it violates the following Content Security Policy directive: “script-src ‘self’ ‘unsafe-eval’ ‘unsafe-inline’”. Note that ‘script-src-elem’ was not explicitly set, so ‘script-src’ is used as a fallback.


Approach 1: Relying on my hunch

Looking at the error, the only spot where I could find the following code from error message is in next.config.mjs

"script-src 'self' 'unsafe-eval' 'unsafe-inline'"
Enter fullscreen mode Exit fullscreen mode

At first, I added but then I realised the other domains such as are without ‘https://’ so I changed it to

Inspecting network calls, Microsoft clarity’s endpoint “/collect” has been getting called as I was switching tabs on my website.

But is this the right way? Definitely not.

Approach 2: Read the documentation to make sure you got it right.

Clarity’s documentation suggests adding Clarity to your default-src directive, but for reasons I do not know, adding Clarity to default-src did not work.

Clarity’s documentation also recommends to add the following

Enter fullscreen mode Exit fullscreen mode

Looks like it wasn’t just but with a * (for load balancing reasons mentioned in the docs)

I would choose approach 2 because I would then have made an informed decision after reading the documentation and finding the right way to fix CSP related issues.

For more information, refer to this stackoverflow question.


Never assume an error is because of X or Y without reading the error message completely, this can save you a significant amount of time. In order to get the Microsoft Clarity integration work with your Next.js app, you need to update a directive in next.config.mjs to allow requests made to

About me:







Top comments (0)