While developing an AMP application with Next JS, everything seems to work perfectly in localhost. However, upon moving to the production environment, I encountered errors related to AMP not being allowed to load its workers.
The initial error message is:
Refused to create a worker from 'blob:' because it violates the Content Security Policy directive: "default-src * data: 'unsafe-eval' 'unsafe-inline'. Since 'worker-src' was not explicitly set, 'default-src' is used instead as a fallback."
After understanding the issue, I noticed that the header sent by Next JS by default restricts loading of blob:
, causing the browser to reject AMP's scripts.
To resolve this, I added a new header in next.config.js
(taking advantage of the feature available in next 9.5) to allow blob for workers:
async function headers() {
return [
{
source: "/",
headers: [
{
key: "Content-Security-Policy",
value: "default-src * data: 'unsafe-eval' 'unsafe-inline'; worker-src blob:;",
},
],
}
];
}
Although the configured header is successfully included in the response, there are still two headers present - one from my configuration and the other being the default header from Next JS.
Despite defining the worker-src policy in my header, the browser fails to recognize it and I continue to encounter the same error.
It's worth noting that using
<meta http-equiv="content-security-policy" />
tag is not a valid option for AMP.
Additionally, the issue seems to only affect specific AMP components like amp-bind and amp-script, while others do not pose a problem.
If anyone has a solution to this dilemma, I would greatly appreciate your insights. Thank you for taking the time to read through this.