Accessing the AppContext in Next.js within the _document file is the

My challenge with using next js is the occurrence of Content-Security-Policy issues due to the inline styles it utilizes.

If 'unsafe-inline' is not added to the style-src, you will encounter the error message 'Refused to apply inline style because it violates the following Content Security Policy directive.'

However, allowing 'unsafe-inline' poses security risks that we want to avoid.

Some related problems and discussions on this matter include:

  1. issue 256
  2. issue 18557

In my case of server-side rendering, the recommended solution involves implementing a CSP in the response header and adding a nonce to the document. For example:

Sample code snippet here...

The drawback of this approach is that having getInitialProps in my _app file means that the getInitialProps at the _document level won't be called.

I can generate the CSP and nonce in the _app's getInitialProps but accessing the nonce in the _document becomes problematic.

Different code snippet here...

As removing getInitialProps from _app would disrupt the application flow, I am exploring ways to share properties between _app and _document or seeking alternative solutions to resolve the CSP issues effectively.

Answer №1

Transferring data from _app to _document may seem impossible as _document is executed first. However, you can utilize the getInitialProps function in both _app and _document separately, eliminating the need to modify your existing _app. Any nonce/csp modifications can be made within _document, prior to _app's execution.

getInitialProps is a function at the component level, meaning it will execute on every component it is applied to, including _document and _app if used in both places. However, it functions solely on the server side, thus nonces won't update with client-side routing changes or live reloading during development mode.

import Document, { Html, Head, Main, NextScript } from 'next/document'

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    const [csp, nonce] = generateCsp()
    ctx?.res?.setHeader('Content-Security-Policy', csp)
    return { ...initialProps, nonce }
  }

  render() {
    return (
      <Html>
        <Head nonce={this.props.nonce} />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

It's important to note that the Head component within _document differs from the one found in next/head. Upon examining the next/head code, there doesn't appear to be support for a nonce prop, necessitating its implementation within _document.

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

What is the most effective approach to invoking a handling function within a React component?

While delving into the ReactJs documentation on Handling events, I found myself pondering about the preferred method for invoking a handling function within a component. A simple yet fundamental question crossed my mind: when should one use either onClick ...

Tips for including shared information across different ionic tabs

Is there a way to include some shared content, like a canvas, in between the content of different tabs in Ionic? I want this common content to be displayed across all tabs, while each tab still shows its own dynamic data below it. I attempted to add the c ...

Creating a custom regex script in Javascript to properly parse Google Sheets data that contains commas

Currently, I am working with a JavaScript script that extracts data from a public Google Sheets feed in a JSON-CSV format that requires parsing. The rows are separated by commas, but the challenge lies in dealing with unescaped commas within each item. Fo ...

Delay the execution of @mouseover in Vue: a guide to managing scope

Looking to implement an action only when the user has hovered over a div for at least 1 second. Here's how it's set up: <div @mouseover="trigger"></div> In the script section: data() { return { hovered: false } } m ...

Is it possible to assign binary content to the src attribute of an img, audio, or video tag?

Picture this scenario: I send an ajax request to my PHP server with the name of an image file, and the server is restricted from sending a direct link to the file. Instead, it must send the file contents using PHP's readfile(); function. Now, when thi ...

Melodic Streaming Platform

I currently have a client-side application built using React. I have a collection of music stored on my Google Drive that I would like to stream online continuously. I lack experience in server-side programming. Can you suggest any resources or steps I s ...

Changing a single variable into an array that holds the variable in JavaScript

Is there a way to change 5 into [5] using JavaScript? I need this functionality for a method that utilizes jQuery's $.inArray. It should be able to handle both scalar variables and arrays, converting scalars into arrays with a single element. ...

When an element is dragged within the mcustomscrollbar container, the scroll does not automatically move downward

I am facing an issue where I have multiple draggable elements inside a Scrollbar using the mcustomscrollbar plugin. When I try to drag one of these elements to a droppable area located below the visible area of the scroller, the scroll does not automatical ...

The error message displayed reads as follows: "topojson has encountered a TypeError: Unable to access the property 'feature' as

Context A problem has arisen with JavaScript when trying to use the topojson.feature(topology, object) function. It seems that this issue appeared after moving from TopoJSON version 1.6.26 to version 2.x, although the functionality remains similar. The p ...

Utilizing Facebook's JavaScript SDK to transmit variables to PHP using ajax

Thank you in advance for your attention. I am trying to utilize the Facebook js SDK to retrieve the user's name and id, and then send them to PHP on the same page (index.php). After successfully obtaining the username and id and storing them in two Ja ...

Filtering an array of objects by multiple arrays of keys

My data set consists of an array of objects const Data = [ {first_name: 'Ammy', city_name: 'LA', age: 22, designation: 'officer'}, {first_name: 'Dave', city_name: 'Paris', age: 23, designation: 'en ...

Looking to extract the full page source with Selenium and Node.js? Having trouble getting the complete source using driver.page_source as it

Having trouble fetching the full page source with Selenium web driver in Node.js I attempted using driver.page_source but it returns undefined in the console if(this.driver.findElement(By.id("ap_error_page_message")).isDisplayed()){ console.log(t ...

"Unleashing the power of React Native: A single button that reveals three different names

I have a piece of code that changes the name of a button from (KEYWORD) to a different one (KEYNOS) each time it is clicked. How can I modify it to change to a third value (KEYCH), where the default name is (A, B, C... etc), the first click shows Numbers ...

Are you familiar with the Puppeteer PDF tool that generates empty pages from the cloud and seamlessly integrates with Postman? What do

After days of searching, tweaking, and deploying, I still can't get this to work. I'm hoping it's just a simple mistake on my part that someone else can help me with. I am attempting to use Puppeteer to generate a PDF from a Node.js Express ...

Show the content of a list from a different URL on a webpage using HTML with the

My current task involves retrieving JSON data using Jquery and then displaying the names in a simple HTML list. Typically, the JSON files I work with have a straightforward format like: [ {a:1,b:2},{a:3,b:4}] However, this time, the JSON file is hosted ...

javascript: revealing the identity of a click event handler

Here I am looking to create a click function with a specific name and parameters for the purpose of code reusability. This will allow me to write one generic function that can be used for common tasks like enabling users to delete various types of data. I ...

Issue with submitting forms in modal using Bootstrap

In the model box below, I am using it for login. When I click on either button, the page just reloads itself. Upon checking in Firebug, I found something like this: localhost\index.php?submit=Login <div class="modal fade" id="loginModal" tabindex= ...

Determining if a swf file has loaded using JavaScript and swfobject

Here is the code snippet I am working with: <head> # load js <script> function graph() { swfobject.embedSWF( "open-flash-chart.swf", "chart", "400", "180", "9.0.0", "expressInstall.swf", {"data-file":"{% url moni ...

I desire to incorporate a subtle fading effect into the script

I have written the script code and now I am looking to add a fade effect to it. Can anyone guide me on how to achieve this? Your help is much appreciated! ※I used an online translator as English is not my native language. Please bear with any awkward ph ...

ES6 does not work with React hello world

Can anyone help me with troubleshooting my code? I've checked the console on jsbin and can't find any errors. http://jsbin.com/susumidode/edit?js,console,output Class secondComponenent extends React.Component { render(){ return ( &l ...