How I fixed this Next.js error: Refused to load the script ‘some_script_url’ because it violate the following Content Security Policy directive
Recently, I migrated my portfolio website: ramunarasinga.com to Next.js using leerob.io 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 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.
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
https://*.clarity.ms https://c.bing.com
Looks like it wasn’t just www.clarity.ms 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.
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 clarity.ms
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.