What is the process for including external JavaScript in Next.js?

I've been diving into Next.js and I'm struggling to incorporate external JavaScript into my project.

Specifically, I'm trying to include a script named query.js into the /pages/index.js file.

console.log("script loaded!")
function hello(){
    console.log("hello!")
}

The script successfully loads when I import it in _app.js

import '../styles/globals.css'
import '../public/static/query.js'

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

export default MyApp

However, attempting to call the function like this in index.js results in "ReferenceError: hello is not defined", even though the script has loaded.

export default function Home() {
  return (
  /* some div */
  {hello()}
  /* the rest of the code */
  )

What could I have done incorrectly? My goal is to utilize the script for data processing on the browser. I have experimented with different approaches without success.

Answer №1

It all comes down to how you intend to bring in your JS file.

Your current method

The current way you're handling it involves creating a module that only has side effects, which gets triggered when imported - hence the appearance of the console.log statement. To resolve this, you can simply attach the hello function to the window object, although this is not recommended.

Suggested approach

Typically, it's better to have modules without side effects. In this case, you should export your function and import it wherever necessary to make everything run smoothly. Here's an illustration:

console.log("script loaded!")
export function hello(){
    console.log("hello!")
}

Then, in your module

import {hello} from 'wherever';

export default function Home() {
  return (
  /* some div */
  {hello()}
  /* the rest of the code */
)

Answer №2

If you want to include external JavaScript in Next.js, you have the option of using the Script component found in the next/script package starting from version 11.0.0.

Here is an example taken from their official website:

import Script from 'next/script'

export default function Home() {
  return (
    <>
      <Script src="https://www.google-analytics.com/analytics.js" />
    </>
  )
}

For more information, you can refer to their official documentation.

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 value of a Vuetify v-select input element does not remain stored within it

My Vuetify v-select component is set up like this: <v-select :name="search['type']" v-model="type" :items="typeOptions" label="Type" > </v-select> The typeOptions array looks like this: typeOptions: [ { text: ...

Sending JavaScript Variables to MySQL Database via PHP

I'm currently attempting to pass a JavaScript variable to PHP, but I'm unsure of the best method to do this. I've heard about Ajax, but I haven't used it before and find it difficult to understand. Can anyone suggest an easier way to ac ...

How to efficiently load 3000 objects in Openlayers using IE8

One of my clients exclusively uses IE8 and is working with an openlayers map. He is trying to load 3000 polygons onto the map, which Chrome and IE9 can handle without any issues. However, IE8 freezes when attempting to load the objects. These objects are c ...

RaphaelJS: Ensuring Consistent Size of SVG Path Shapes

I am currently constructing a website that features an SVG map of the United States using the user-friendly usmap jQuery plugin powered by Raphael. An event is triggered when an individual state on the map is clicked. However, when rendering a single stat ...

Using React to fetch data and then mapping it inside a function

I am facing an issue where I need to make a request for each item in the MAP, but I want to ensure that I wait for the response before moving on to the next object. Currently, my code is sending out all the requests simultaneously, causing the Backend to c ...

What are the steps to deploy Next JS?

For my latest project, I dived into the world of Next JS with Tailwind CSS and decided to use "next build" to compile it. However, after running the command, it generated a folder named ".next", but surprisingly no .html files were found within. Coming fr ...

Sending data to functions

Hello all, I'm a beginner with Vue so please bear with me :) I am facing a challenge where I have a function that retrieves user attributes and based on those attributes, I need to run a GraphQL query in another function. Both functions are under the ...

NUXT: Module node:fs not found

Encountering an error when running yarn generate in a Kubernetes container during production. The same command works fine locally and was also functioning properly in production up until last week. Error: Cannot find module 'node:fs' Require stac ...

Does v-if cause the jquery clock picker to malfunction?

Here is my unique div where the clockpicker library functions correctly. <div class="input-group clockpicker"> <input type="text" class="form-control" value="18:00"> <span class="input-group-addon"> <span class ...

The JSON data response is not being properly displayed on the div element

I am having trouble with the success function in my ajax call. The data is processed correctly in the view and the ajax call works fine, but for some reason, the data is not getting appended to the div. Here is my jQuery: $(document).ready(function() { ...

Analyze the length of time and provide a percentage of similarity

Is it possible to compare two durations and calculate the percentage of similarity? Suppose I have a reference duration, as well as a second duration that needs to be compared with the first one. There is an 8% tolerance level, meaning that the second du ...

Nuxt3 - Issue with Accessing Environmental Variable in Pinia Store

I've encountered an issue while trying to access the BASE_URL from the environment in a Pinia store within Nuxt using runtimeConfig, resulting in a 500 Nuxt instance unavailable error. Below is the error image link: https://i.sstatic.net/hOZF7.png ...

Extract information from a URL without the need for a page reload or user interaction

Recently, I developed a form that accepts YouTube links and extracts the ID using parsing/regex. The function is triggered by clicking a button, which then displays the ID of the URL. Is there a way to show the ID without requiring a button click or page ...

Struggling with loading react storybook

I am having trouble getting my storybook app to start. It is stuck in a loading state with no errors showing in the console. Can anyone help me figure out what I am doing wrong? Check out the screenshot here storybook/main.js const path = require(' ...

What is the process for incorporating the Angular JS $q service into this specific scenario?

Looking at the example below, it's essential to ensure that the drawFunc method completes before proceeding to add the opacity and ultimately including foregroundPath to the Kinetic layer. Is there a way to effectively "wait" for the value of foregro ...

Encountered an issue while setting up ng-circle-progress in Angular: Unable to find an exported member in

I am currently working on incorporating the ng-circle-progress functionality by referring to the documentation at https://www.npmjs.com/package/ng-circle-progress. Here is a snippet from the .ts file: import { Component } from '@angular/core'; i ...

Arranging various JavaScript arrays

I've been working on a script using the Haversine formula, but I'm running into an issue where it always directs me to the first location in the array, no matter how many times I switch them around. Any suggestions? var locations = new Array( ...

Establish a buffering system for the <video> element

Currently, I am facing an issue with playing videos from a remote server as they take an extended amount of time to start. It appears that the entire video must be downloaded before playback begins. Is there a way to configure the videos so they can begi ...

Need to create a callback within a sequence of events?

Is it possible to create a callback chain like this? Widget.update(...).onUpdate(function(data){ console.log('updated'); }); Here is the current code snippet: var Gateway = {}; Gateway.put = function(url, data, callback) { $.ajax({ ...

Having trouble displaying results in Vue.js after making an API request?

I am facing challenges in displaying the results using vue.js. The data from my API (ASP.NET CORE) is being retrieved successfully, as shown in my vue dev tools on Google Chrome. However, I am encountering difficulties in rendering the results on the brows ...