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 best way to create an animation where every letter in a word transitions to a different

Is there a way to animate a word so that each letter changes color within a range of 7 colors, with all letters displaying different colors simultaneously in an infinite loop? <div class="box"> <h1 class="logo animate__animated an ...

Binding hover and load events using jQuery on elements that are dynamically generated

One should note that the click event can be successfully bound to an element with the class name keybox, even if this element is dynamically generated. The code for this would look like: $('body').on('click', '.keybox', funct ...

Retrieve a variety of items and pass them to a view using the mssql module in Node

I'm facing an issue while trying to retrieve data from multiple tables and pass them to my view. Below is the snippet of code I've written that's causing the error. router.get('/', function(req, res, next) { sql.connect(config ...

"An error occurs when trying to trigger a .click() event within a list element

There is a list that can contain either plain text or a link. If there is a link present, the entire list element should be clickable. When attempting to execute the following code: if ($('.link').length) { $('li[data-contains-link]' ...

Looking for a way to pass data to a dynamic page in NextJS without using props? I attempted to avoid unnecessary network calls and reuse data by experimenting with React Context, but have

I am currently developing a NextJS project where I am in the process of generating a report for different projects. On the project details page, there is a link that redirects to a dynamic report that utilizes the specific details of the project displayed ...

Tips for utilizing Material UI's Tooltip feature alongside a TableRow

I'm currently facing an issue where I'm trying to include a MUI TableRow inside a Tooltip component in order to display a long uuid when hovering over the row. However, I noticed that all the columns of the row are being compressed into the first ...

Is there a way to trigger a "click" on a webpage without physically clicking? So that I can preview the response message before actually clicking

Is it possible to generate a "mock" request to a server through a website in order to examine the response before sending the actual request? Let me clarify with an example: if I were to click on a button on a website, it displays a certain message. I am ...

Utilizing Squelize's junction table for forming new connections: a comprehensive guide

I am currently working with three basic tables: A, B, and C. The relationship between A and B is many-to-many, so I am using a junction table called A_B. Table C has a one-to-many relationship with the junction table A_B. In sequelize, this is how they are ...

Stop jQuery Tab from Initiating Transition Effect on Current Tab

Currently, I am utilizing jQuery tabs that have a slide effect whenever you click on them. My query is: How can one prevent the slide effect from occurring on the active tab if it is clicked again? Below is the snippet of my jQUery code: $(document).read ...

Retrieve the radio button value without using a key when submitting a form in JSON

Looking to extract the value upon form submission in Angular, here is the code: In my Typescript: constructor(public navCtrl: NavController, public navParams: NavParams, public modalCtrl: ModalController, public formBuilder: FormBuilder, public alertCtrl ...

Do ES6 features get transpiled into ES5 when utilized in TypeScript?

After implementing ES6 features such as template strings, arrow functions, and destructuring in a TypeScript file, I compile the code to regular JavaScript... Does the TypeScript compiler also compile the ES6 syntax, or do I need to utilize another compil ...

using hover/click functionality with a group of DIV elements

I have a group of DIV elements that I want to apply an effect to when hovering over them with the mouse. Additionally, when one of the DIVs is clicked, it should maintain the hover effect until another DIV is clicked. <div class="items" id="item1"> ...

Unit test produced an unforeseen outcome when executing the function with the setTimeout() method

When manually testing this code in the browser's console, it performs as expected. The correct number of points is displayed with a one-second delay in the console. const defer = (func, ms) => { return function() { setTimeout(() => func.ca ...

Exploring the boundaries of HTML data manipulation using JavaScript or jQuery

In my HTML (within a Twig template), there is the following code snippet: <li id="{{folder.id}}" data-jstree='{"icon":"glyphicon glyphicon-tags", "type":"folder"}' ><a href="#">{{folder.name}}</a> I'm attempting to extrac ...

Combining two JSON objects with sailsjs-nodejs to create a single merged object

Hello everyone, I am a beginner with Sailsjs-Nodejs. Currently, I have two JSON Objects in my controller that I need to merge/join in order to create a third object to send as a response. The output when using res.send(obj1) is: [ { total_fare: "37 ...

Using AngularJS to send a model to ui-select

Here is the scenario at hand: A form includes a directive known as <timeZone ng-model="formModel.timeZone" This directive communicates with a web service to fetch timezone information The directive then presents the timezones in a ui-select dropdown ...

Supply context to node package

I've encountered an issue with the code below, where sometimes the content is not passed correctly: var app = require('buildersApps'); app.addContent({ folderPath: __dirname + '/content/' }); app.start(); To address thi ...

JavaScript Array Objects

As a newcomer to the world of Javascript, I've decided to take on the challenge of creating a blackjack game. Utilizing arrays and objects for my game: card = {}, //each card is represented as an object with suit, number, and points properties playe ...

When using the map function, I am receiving an empty item instead of the intended item based on a condition

Need assistance with my Reducer in ngRx. I am trying to create a single item from an item matching an if condition, but only getting an empty item. Can someone please help me out? This is the code for the Reducer: on(rawSignalsActions.changeRangeSchema, ...

Error: Attempting to access property 'error' of an undefined object resulted in an unhandled exception

I encountered an error when using the handleSubmit function in the Register component: Uncaught (in promise) TypeError: Cannot read property 'error' of undefined. Below, you can see the code for the component, how I fetch API data, and the Next. ...