Issues with Content-Security-Policy Implementation in Next JS and AMP Technology

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.

Answer №1

When utilizing multiple CSPs, the browser will only permit what is allowed in ALL CSPs. Even if your custom CSP allows it, the default next JS CSP will block blob content. It may be necessary to eliminate one of the CSPs and adjust the other to meet your specific requirements.

For more information, refer to the "Multiple content security policies" section at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unforeseen outcomes when setting background colors with Anime.js

I've recently started experimenting with Anime.js. I have a piece of code that I'm using to animate a div element with an id of a. anime({ targets: "#a", translateX: 250, color: "#fff", backgroundColor: "hsl(200, 50%, 50%)", ...

The npm gray-matter library is experiencing compatibility issues with the most recent versions of Next.js and Node.js

Currently utilizing the latest version of nextjs, I am facing an issue with displaying markdown blogs using gray-matter. Despite referring to the example provided on the official documentation https://www.npmjs.com/package/gray-matter, it does not seem to ...

Error in TypeScript: Typography type does not accept 'string' type as valid

As I attempt to implement the Typography component from material-ui using TypeScript, I encounter a perplexing error message TypeScript is throwing an error: Type 'string' is not assignable to type 'ComponentClass<HTMLAttributes<HTMLE ...

Concealing a button once the collapse feature is toggled in Bootstrap

The following code snippet from the bootstrap website demonstrates how to use collapse functionality: <a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample"> Link with href & ...

Adjusting window size when page is resized

While browsing through SO, I stumbled upon this interesting piece of code: var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0], x = w.innerWidth || e.clientWidth || g.clientWidth, y = w. ...

Incorporating an array of JSON into a Mongoose schema in JavaScript

I am currently developing an Android App focused on baseball, and I have decided to use MongoDB to store my data. The format in which I would like my JSON data stored in the database is as follows: {"<a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Guide to combining an Angular 2 application with a Django application

Currently, I have been working through the Tour of Heroes tutorial. The structure of my Django app can be simplified as shown below: apps/my_app/migrations/ apps/my_app/__init__.py apps/my_app/urls.py apps/my_app/views.py frontend_stuff/js/ javascript ...

Combining load and change events in jQuery at the same time

Often times, I find myself needing to attach a behavior to an element both after it has loaded and after a specific event has been triggered (such as "change"). I believe the most efficient approach would be to combine these actions in one line: $('# ...

Can Google's bot initiate JavaScript click events on a website and how can this be resolved?

Currently, we are facing an issue with the reviews on our website. In order to optimize page load speed on both desktop and mobile, we have decided to initially display only 10 reviews. After each button click by the user, the next set of 10 reviews is loa ...

Discovering a device's model using JavaScript

How can I use Javascript to redirect users to different download pages based on their device model? ...

Sails.js seems to be malfunctioning, as it does not seem to be recognizing the term 'sails'

It seems like I'm encountering an issue with the 'sails' command not being recognized on my Windows 10 system. Despite following all the installation steps, including globally installing Sails.js through npm and ensuring Node is installed, I ...

How to utilize dot notation in HTML to iterate through nested JSON in AngularJS?

I'm struggling with displaying nested objects loaded from a JSON file in Angular. I've seen examples of using dot notations in HTML to access nested data, but I'm new to Angular and can't seem to get it right. The JSON is valid, but I j ...

Tips for updating the class of a button upon clicking it

I have a dilemma with my two buttons - one is green and the other has no background. I want them to change appearance when clicked, from green to one with a dashed border-bottom style. Below is the HTML code for these buttons: <div class="btns"> ...

The appearance of the upload button in React using Material-UI seems off

After following the MUI document on React Button upload, I noticed that the UI results were different than expected. Instead of just showing the button UI, there was an additional UI element present. By adding the sx={{display:'none'}} property, ...

Set the style to be displayed as a block element

I am working on a Rails application that contains some <li> elements with the CSS property display: none;. I want these elements to only appear on the page when they are being dragged. However, there are some elements that do not have the display: no ...

What is the sequence in which middleware and callback functions are executed in Node.js?

I'm just starting out with node.js, and I have a file called app.js that references another file named xmlParser.js. The purpose of this is to parse an input xml file using the xml2js node module. Here's a snippet from app.js: //Require modules ...

JavaScript Document Object Model: Locate an element with a class that is either similar to or includes a specific substring

I am facing a situation where I need to locate a wrapper element with a specific class name that includes a random id, such as wp-rgtayfu-fxyjzw-wrapper. The class will always have the substring wrapper in it, and there is only one element in the document ...

Error: Trying to use 'setTimeout' before it has been initialized is not allowed

I'm currently working on a JavaScript exercise in my code. I encountered an issue where I am trying to assign a reference to the setTimeout function to ogTimeout on the second line since I plan to redefine setTimeout later. However, when I run the co ...

What is the process for duplicating a set of elements within an svg file and displaying the duplicate at a specific location?

SVG <svg width="200" height="200"> <g id="group"> <rect x="10" y="10" width="50" height="20" fill="teal"></rect> <circle cx=" ...

When utilizing a React styled component, it functions smoothly during development but triggers a build error when in production

Recently, I encountered a strange issue with my code. I have a styled component div that wraps around another component in this manner: <ContentWidget> <BookDay /> </ContentWidget> (The Bookday component returns an empty div so there ...