Enhance the script tags in Next JS by incorporating data attributes

After compiling my Next JS app, it creates a list of script files for inclusion in the following format.

<script src="/_next/static/chunks/main-1234.js" async=""></script>
<script src="/_next/static/chunks/webpack-1234.js" async=""></script>
<script src="/_next/static/chunks/framework.1234.js" async=""></script>
<script src="/_next/static/chunks/1234.5678.js" async=""></script>
<script src="/_next/static/chunks/commons.1234.js" async=""></script>
<script src="/_next/static/chunks/pages/_app-1234.js" async=""></script>
<script src="/_next/static/chunks/1234.5678.js" async=""></script>
<script src="/_next/static/chunks/pages/%5B%5B...path%5D%5D-1234.js" async=""></script>
<script src="/_next/static/1234/_buildManifest.js" async=""></script>
<script src="/_next/static/1234/_ssgManifest.js" async=""></script>

I am looking to insert a custom data attribute into certain scripts as shown below.

<script data-cookieconsent="ignore" src="/_next/static/chunks/pages/%5B%5B...path%5D%5D-1234.js" async=""></script>

I have been investigating ways to achieve this in the next.config.js file since I understand that webpack overrides can be implemented there, but so far, I haven't found a method to include data attributes in dynamically generated js files like these.

Answer №1

Implementing in Next.js 11

To implement this feature in Next.js 11, you will need to extend and modify the getScripts method from the Head class within your _document.js file.

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

class CustomHead extends Head {
    getScripts(files) {
        const originalScripts = super.getScripts(files);
        return originalScripts.map((script) => {
            return React.cloneElement(script, {
                'data-cookieconsent': this.props.cookieconsent
            });
        });
    }
}

class CustomDocument extends Document {
    render() {
        return (
            <Html>
                <CustomHead cookieconsent="ignore" />
                <body>
                    <Main />
                    <NextScript />
                </body>
            </Html>
        )
    }
}

export default CustomDocument

In Previous Versions of Next.js

If you are using a version of Next.js before 11, an alternative approach is to extend the NextScript class within your _document.js file. This allows you to include custom data-* attributes in the generated scripts by Next.js.

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

class CustomNextScript extends NextScript {
    getScripts(files) {
        const originalScripts = super.getScripts(files);
        return originalScripts.map((script) => {
            return React.cloneElement(script, {
                'data-cookieconsent': this.props.cookieconsent
            });
        });
    }
}

class CustomDocument extends Document {
    render() {
        return (
            <Html>
                <Head />
                <body>
                    <Main />
                    <CustomNextScript cookieconsent="ignore" />
                </body>
            </Html>
        )
    }
}

export default CustomDocument

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

The ng-app directive for the Angular project was exclusively located in the vendor.bundle.js.map file

Currently, I am diving into an Angular project that has been assigned to me. To get started, I use the command "gulp serve" and then access the development server through Chrome by clicking on "http://localhost:3000". During my investigation in Visual Stu ...

Exploring Vue.js: Navigating through child components from parent component

I currently have 3 components in my project: Form, Card, and Button. Let's start with the Button.vue component: <template> <div> <slot v-bind="{ text }"> <button>{{ text }}</button> </slot> ...

Struggling to generate an HTML table using JSON data

Struggling with generating an HTML table from JSON data, I'm inexperienced and having trouble with the logic. The JSON data I have needs to populate a complex dynamic HTML table. The design of the table is intricate, making it challenging for me to i ...

Clicking buttons in AngularJS

I've developed a button that, when clicked, triggers an AJAX call and binds the server response obtained through AJAX to a table using AngularJS. The issue I'm facing is that the data should appear on the webpage on the first click of the button, ...

How can I efficiently display three items per click when tapping into jQuery data?

Here is the code that I have been working on: jQuery(document).ready(function( $ ) { var $container = $('#homegrid').masonry({ isAnimated: true, itemSelector: '.home-blocks', columnWidth: '.grid-sizer ...

What is the best way to implement session timeout specifically for inactive users?

My code is displaying a timeout counter every 2 minutes, even if the user is active and interacting with the screen. I only want the timeout to occur for idle users. How can I implement this in my code? I have created two webforms default.aspx and sessionT ...

JsPlumb: Incorrect endpoint drawn if the source `div` is a child of a `div` with `position:absolute`

My current setup involves two blue div elements connected by jsPlumb. You can view the setup here: https://jsfiddle.net/b6phv6dk/1/ The source div is nested within a third black div that is positioned 100px from the top using position: absolute;. It appe ...

Developing HTML5 animation by utilizing sprite sheets

Struggling to create an engaging canvas animation with the image provided in the link below. Please take a look at https://i.stack.imgur.com/Pv2sI.jpg I'm attempting to run this sprite sheet image for a normal animation, but unfortunately, I seem to ...

Exploring the capabilities of arrays within Ajax

Below is the original code I wrote in JavaScript: var wt_val = []; for (i = 0; i<human_wt.length; i++){ var mult; mult = data_list[basket_list[button_port_name][i]].map(x => x*(wt[i]/100)); wt_val.push(mult); ...

Locate components within the Data object of jQuery's .get() method

It's proving to be a bit more challenging than I initially thought :) $.get('/page.html', function(data) { //extract only the elements with the "contents" class }); I'm struggling to figure out the best way to achieve that. ...

Having trouble decoding audio data in JavaScript Web Audio?

I'm attempting to utilize the Web Audio API in JavaScript to upload a sound into a buffer and play it. However, I am encountering an issue where it does not work and an error message is displayed: Uncaught TypeError: Failed to set the 'buffer&ap ...

Mapbox GL JS stops displaying layers once a specific zoom level or distance threshold is reached

My map is using mapbox-gl and consists of only two layers: a marker and a circle that is centered on a specific point. The distance is dynamic, based on a predefined distance in meters. The issue I'm facing is that as I zoom in and move away from the ...

Implement the static middleware to host static files using express

I have recently organized my folders in the following structure: /app server.js /public 1.jpg My goal is to access the 1.jpg image using the URL /1.jpg. To achieve this, I made changes to my server.js file by including the following middleware a ...

Positioning Images at the Top of the Screen in React Native

I have two images that I would like to display side by side at the top of the screen. <View style={styles.container}> <View style={styles.topWrapper}> <Image source={TOP_START_GRAPHIC} style={styles.topStartImage} /> ...

Syntax for the expression used in the ng-click directive

I have two variables named wkidx and dyidx. My goal is to create multiple collapsible elements on the same page using the angular ui bootstrap directive. I am currently facing an issue with the following code snippet: <a href="" class="" ...

The functionality of the OnClientClick event within the ASP.NET platform

While utilizing ASP.NET to pass a value to a JavaScript function, I encountered an issue where it doesn't seem to work when trying to pass a value from another control. It seems to behave as if there is a syntax error and just reverts back to the main ...

Using this functionality on a ReactJS Functional Component

Hey everyone, I'm fairly new to using React and I'm currently trying to wrap my head around some concepts. After doing some research online, I stumbled upon a situation where I am unsure if I can achieve what I need. I have a functional componen ...

Update the class of the appropriate navigation tab when the corresponding div is scrolled into view

After reading similar questions and doing some research on scrollspy, I don't think it will provide the functionality I need. It seems to only support bootstrap style highlighting. If there is more to it that I'm not aware of, please inform me! ...

I am encountering an error that states: UnhandledPromiseRejectionWarning: TypeError: Unable to retrieve the property 'buffer' as it is undefined

I am facing an issue with my code where I am unable to upload new files to my website. Can someone help me understand what might be causing this problem? const multer = require("multer"); const upload = multer({ storage: multer.memoryStorage() ...

Understanding Variable Scope in JavaScript: How Variables are Accessed in Different Functions

I've been experimenting with a script that utilizes jQuery's get function to transfer data to another page and display the returned information as an alert on the current page. My goal is to send both the search field value from an input form (wh ...