Is it possible to utilize a JavaScript file for creating inline JavaScript in Next.js?

I am facing an issue with a third-party script that requires me to define a global window.varforthem before it loads. I checked the nextJS documentation but implementing it as suggested seems less readable and conflicts with eslint and other plugins. Additionally, placing the script in my public folder using

<Script src="/scripts/forthirdparty.js" />
results in it not being optimized like other assets in _next/static, plus its max-age header is set to 0 preventing CDN caching. Can you suggest a better approach or guide me on setting a custom max age for this static file?

I attempted using a regular <script> tag instead of <Script> within the <Head> element based on Steve Tomlin's advice.

The inline scripts require server configuration making the situation more complex.

// earlier in the method
const conf = `window.config = ${JSON.stringify(pageProps.config)}`;
const { config: pageConfig } = pageProps;

// later on
<Head>
  <script
    dangerouslySetInnerHTML={{
      __html: conf,
    }}
  />
  <script src="/scripts/myfile.js" />
  <script src={pageConfig.third_party_script_url} />
</Head>

Upon inspecting the <head> tag in Chrome, everything appears correct. However, nothing executes and I encounter the error message

Did not expect server HTML to contain a <div> in <div>.
The initial load works after compilation, but subsequent refreshes fail. It perplexes me why the rendering differs between server and client environments.

Answer №1

Here's a helpful tip for anyone experiencing timing issues with incorporating external JavaScript in Next.JS. In my case, the third party script was manipulating the DOM either before or after React detected the changes made by the server. To resolve this issue, I decided to include <script> tags within the <Head> element for my own scripts, which simply contained configuration settings for the third party script. By keeping the third party <script> tags outside of the <Head>, they were rendered at the bottom of the page after all other scripts had run.

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 Node.js to return JSON data containing base64 encoded images

In my database, I store all images as base64 with additional data (creation date, likes, owner, etc). I would like to create a /pictures GET endpoint that returns a JSON object containing the image data, for example: Image Data [{ "creation": 1479567 ...

What is the best method to extract information from an ever-changing external JSON file?

I am currently in the process of developing a discord bot using discord.js, and one of the features I am trying to implement is a command that displays the current bitcoin price. To achieve this, I am utilizing the CoinDesk API which provides the necessary ...

Creating a compact, production-ready code using the webapp generator in Gulp

I recently used the webapp generator to scaffold a project, but encountered an issue where the project only worked when accessed through localhost and not when opening the files directly in the browser with a file scheme. The URL http://localhost:9000/ cor ...

Attempting to deploy my node.js application on Heroku resulted in an error message saying that the web process failed to bind to $PORT within 60 seconds of launch, causing the process to exit with status

I recently encountered an issue while attempting to deploy my node.js app on Heroku. The error message stated that the Web process failed to bind to $PORT within 60 seconds of launch, and the Process exited with status 137. I'm unsure of how to resolv ...

Change the way a button interacts with a different element

Currently, I am utilizing SlickSlider from http://kenwheeler.github.io/slick/ and attempting to integrate the Next and Prev buttons with other elements (specifically spans within another container). I have attempted the following: $('button.next&apo ...

Having trouble viewing the footer because I can't scroll down

Hey there! I'm a first-year student from the Netherlands studying ICT&Media Design, and currently tackling projects involving HTML/CSS/JavaScript. As I was working on my personal page to practice with these languages, I encountered some issues. ...

Watching the $scope variable using $watch will result in triggering even when ng-if directive is used, displaying

Encountering an unusual behavior in AngularJS that may appear to be a bug, but there could be a logical explanation. A certain value is being passed to a directive as an attribute. Within this directive, the parameter is being watched using $scope.$watch. ...

Tips for Storing Your Data Collection: A Guide on Different Storage Options

In the different parts of my app, I require access to a dataset containing timezones. Traditionally, I have stored such data in a class method like Timezone.all_zones (Ruby) for easy accessibility anywhere in my code. Is there a way to achieve this same ...

Using TypeScript's interfaces to push items

Can anyone provide some guidance on working with interfaces in typescript? I currently have the following 3 interfaces: export interface HomeMenu { [name: string]: MenuItem; } export interface MenuItem { title: string; route: string; hom ...

How can a node be added between two nodes based on an attribute condition?

Is there a jQuery function, or perhaps another library function, that allows for the insertion of a node (div) between two other nodes (divs) based on its attribute? For instance: Assume I have the following HTML code: <div value=111/> <div val ...

Using ReactJS to search for and replace strings within an array

A feature of my tool enables users to input a string into a textfield and then checks if any words in the input match with a predetermined array. If the user's string contains a specific name from the array, I aim to replace it with a hyperlink. I&a ...

Is there a method to incorporate a scroll event into the ng-multi-selectdropdown, a npm package?

Query: I need to incorporate a scroll event in the given html code that triggers when the div is scrolled. However, I am facing issues with implementing a scroll event that works when the elements are being scrolled. <ng-mult ...

Having trouble retrieving JSON data from backend server in Svelte framework

My goal is to retrieve JSON data from the Backend, specifically information about music videos. It should be a simple task, but I am encountering some difficulties. I attempted to follow a tutorial provided at: . The tutorial demonstrated fetching data wi ...

Checking for different elements between two arrays in AngularJS can be achieved by iterating through

I am working with two arrays: $scope.blinkingBoxes=[1,3,2] In addition, I have another array named $scope.clickedBoxes where I push several values. Currently, I use the following code to determine if the arrays are identical: if(angular.equals($scope.bli ...

What is the best way to retrieve unique values from my MongoDB database?

My goal is to retrieve all the values of the property "Alimento" in my application. { "foods": [ { "_id": "6318c906904b22a684659009", "Alimento": "Papinha Infantil de Amei ...

the session data is being mishandled

I have integrated express-session and express-mysql-session in my application to handle sessions and store them in a MySQL database. The session data is saved in a table named "sessions". const express = require('express'); const session = requir ...

Struggling to integrate the c3 chart library with Angular, encountering loading issues

I've been attempting to utilize the c3 angular charts, but unfortunately nothing is displaying on my page. Despite checking for console errors and following a tutorial, I still can't seem to get anything to show up. I have cloned the git repo an ...

What is the process for creating a 3D scene using an SVG image?

Recently, I came across an SVG image that caught my eye: https://i.sstatic.net/hTsA1.png Now, I am looking to recreate a similar image like this: https://i.sstatic.net/JWrjz.png Any ideas on how I could achieve this using three.js or another JavaScript 3 ...

Preventing pop-up windows from appearing when triggered by a mouse click event

I am looking for a solution to trigger a popup window when a user right-clicks on a specific area. Here is the current code I am using: $("#popup").bind('mousedown', function(e) { var w; if(e.which==3) { w=window.open('link& ...

JS - what could be causing this to not work properly? Could there be a bug that

Can anyone help me troubleshoot this code? It is supposed to add a search parameter page=value to the URL and load the page, but it's not working. I'm not sure if there's a typo in there. $(function(){ $('.page').on('cl ...