Why is it that my NextJS public script isn't being bundled?

I am facing an issue with three components interacting and I need help in properly bundling them together.

  1. There is dynamic configuration on the page that exists within an inline script
  2. A static script located in the public folder which utilizes the dynamic config to create a global object for a third-party script
  3. The third-party script itself

The code snippet in question looks like this:

const { config: pageConfig } = pageProps;
<Script
    dangerouslySetInnerHTML={{
    __html: `window.config = ${JSON.stringify(pageConfig)};`,
    }}
/>
<Script src="/scripts/mypublicfile.js" />
<Script src={pageConfig.identity.script_url} />

When executed, the output places the script tags right at the end of the <body> tag as follows:

<script>window.config = { values: "iexpected"}</script>
<script src="/scripts/mypublicfile.js" />
<script src="https://www.thirdparty.com"></script>

My goal is to have the first two script tags appear in the actual <head> section, with the inline script taking precedence, followed by my public file script being included in the bundle under _next/static/. The third-party script can remain after these or at the end of the <body> tag.

This is the desired output (without mentioning the standalone public script):

<script>window.config = { values: "iexpected"}</script>
<script src="/_next/static/bundle1.js" />
<script src="/_next/static/bundle2.js" />
<script src="https://www.thirdparty.com"></script>

Essentially, I want my CDN to cache only what's inside _next/static without needing additional configuration for scripts setting a default max-age of 0.

I have attempted various approaches but haven't been able to resolve it. Could it be related to my usage of getInitialProps? I previously thought it impacted the generation of HTML pages only, but could it also affect the bundling process?

Answer №1

I haven't personally tested it, but you might find some help by checking out the documentation at https://nextjs.org/docs/api-reference/next/head for loading scripts in the head section. Additionally, take a look at https://nextjs.org/docs/basic-features/script to see how using the beforeInteractive flag on the script could impact its bundling and loading process.

import Script from 'next/script'

<Script
  src='https://example.com/public/script.js'
  strategy="beforeInteractive"
/>

If that doesn't work, you can also try using the head tag with the async attribute.

import Head from 'next/head'

<Head>
  <script async src='https://example.com/public/script.js'/>
</Head>

Answer №2

After spending half a day working on it, I finally discovered a neat trick - simply import your mypublicfile.js from within your page's implementation and watch as it gets seamlessly added to the bundles served to the front-end and loaded in the browser. Just remember to wrap the import statement in a conditional check to prevent server-side loading. To put it simply:

// pages/mypage.tsx

// Your regular imports
import Image from "next/image";

// Load on the front-end
if (typeof window !== "undefined") {
  import(
    "../scripts/mypublicfile.js"
  );
}

// Your page's implementation
export default function MyPage() {
  return (
    <Image ... />
  );
}

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

Using JavaScript regex to extract the text within a string

I have a specific string that needs to be extracted let str="[a54hy 8:45pm],[f57gh 9:20]" I am looking to retrieve [f57gh 9:20pm] Splitting the string is not an option due to its varying length ...

Issues with grunt - Alert: Task "ngAnnotate:dist" has encountered an error. Proceed using --force option

Encountering an unexpected issue with a Grunt task that previously ran smoothly. The error message is as follows: Running "ngAnnotate:dist" (ngAnnotate) task Generating ".tmp/concat/scripts/scripts.js" from: ".tmp/concat/scripts/scripts.js"...ERROR >& ...

Ensure that the cursor is consistently positioned at the end within a contenteditable div

I'm working on a project where I need to always set the caret position at the end of the text. By default, this works fine but when dynamically adding text, the caret position changes to the starting point in Chrome and Firefox (Internet Explorer is s ...

React Native: When attempting to start `babel-node src` using Nodemon, I encountered an error stating that "babel-node" is not recognized as an internal or external command. This occurred while trying to run the command 'npm run dev

I'm experiencing an issue while using nodemon to launch a React Native app with a simple hello world example. The problem arises when I run the command "npm run dev" and my app crashes because it does not recognize the "babel-node" command. The error ...

Automatically assign a name as an alt attribute

Is there a way in this script to include an alt tag with the value "NikeAir 32" in the given example? <script> function test_options_rendered(){ $('.test_option_value').each(function(){ if( !$(this).parent().hasCla ...

What is the best way to sift through slug data?

Struggling to display related posts from the same category in my project using Sanity for slug data. Attempted fetching all data and storing it in the state but unsure how to filter based on the current post's category. I'm thinking about leverag ...

jquery activating the toggle function to switch between child elements

I'm facing a challenge where I can't use .children() in this scenario, as it won't work since the elements aren't technically children. Here's the snippet of HTML that I'm working with: <p class="l1">A</p> ...

An easy guide to automating the clicking of a javascript 'a href' link in Internet Explorer using Excel

One project I'm currently working on involves using a VBA macro in Excel to automate the process of navigating to specific web pages. Through this automation, I can select elements based on their ID and manipulate them accordingly on the site. Howeve ...

Preventing special characters, numbers, and spaces from being used as the first character in a word in HTML with regular expressions

Is there a way to restrict users from inputting special characters, numbers, and spaces only in the first place of a word using regex in HTML? <label><span>Current Carrier</span></label> <input name='Current Carrier' t ...

Updating the NPM entry point without relying on an index.js file

After successfully publishing a private module to NPM, which contains shared code used by multiple services, I encountered an issue with the transpilation process. Since the code is written in ES6, it needs to be transpiled using Babel before being publish ...

The Swiper example is not compatible with the default settings of Next 13

Swiper is not compatible with Next 13. Using the default React example of Swiper + 'use client' at the top of the page does not yield the expected results. To replicate the issue, follow these steps: Create a bare-bones Next 13 app using this ...

Toggle functionality not functioning correctly when clicking on two elements simultaneously

When I click on the input and the div with class "checkmark", I want the div tag with id "hidden-gift-order" to be hidden. However, clicking on the input works as expected but clicking on the div tag does not. Can someone explain why? function Toggle_Vi ...

What is the best way to conceal the header on a 404 error page?

<HeaderContainer> <Switch> <Route exact path='/counters' component={ParentCounterContainer}/> <Route exact path='/about' component={AboutContainer} /> <Route exact path='/' component={H ...

Is it the right time to implement a JavaScript framework?

Is there a need for using JavaScript frameworks like Angular or React if you are not developing single-page websites or components that receive live updates? ...

Using callback functions to handle parameters in GET requests

Hey there, I'm currently diving into the world of callback functions and I have a burning question that needs clarification. Adding event listeners seems easy enough: $0.addEventListener("click", function(event){console.log(event)}); When you click s ...

Adding data to a URL using jQuery Ajax

I'm currently working on implementing Ajax with jQuery and I have a specific requirement to add data to the URL. Take a look at the code snippet below: var my_website= mysamplesite.com/viewData/"; function displayData(myData) { $.ajax({ t ...

The Jquery confirmation dialogue does not seem to be functioning properly within the Content Place Holder

I've encountered an issue with a JQUERY Confirm dialogue where it works perfectly fine until I place it on a page that is within a masterpage. The confirm alert pops up for a split second and disappears. window.onload = function() { $("#ehi").cli ...

Maintaining the position of the screen as you type in information that is located outside of the container

I am encountering an issue with the input/text-area element in absolute position extending halfway outside the container. The screen position seems to follow the caret as I type, but I'd prefer to keep writing and have part of the text hidden beyond t ...

What is the process for removing a property from the prototype within an array of MongoDB objects?

I have a database in MongoDB/Mongoose where I store user information, including passwords. However, when I want to display a list of contacts on the frontend, I don't want to include the passwords for security reasons. To achieve this, I attempted to ...

The storage capacity of localStorage is insufficient for retaining data

While I was trying to troubleshoot an error, I encountered another issue. var save_button = document.getElementById('overlayBtn'); if(save_button){ save_button.addEventListener('click', updateOutput);} This led to the following ...