Steps to import an external script into a NextJS application and access it from the main bundle

I have encountered an issue while working with the mercadopago library. I need to load the mercadopago script file and create an instance of the MercadoPago object. However, nextJS loads the main bundle before including the mercadopago file, resulting in an execution error due to the undefined object.

I experimented with different methods such as loading the script file into the Head component using a normal tag and also utilizing the Next/Script object like so:

<script src="https://sdk.mercadopago.com/js/v2" strategy="beforeInteractive"/>

Despite trying various approaches, Next always ends up loading the script after the main bundle file. Implementing a setTimeout function to wait for the Mercadopago object to be instantiated does work, but it is not an ideal solution. How can I correctly resolve this issue?

Answer №1

Make sure to load the script in _document.js before any next.js scripts. To do this, create a new file named _document.js in the pages directory and customize it according to your needs.

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

export default class CustomDocument extends Document {
  render(){
    return (
      <Html>
        <Head>      
           /*Include the necessary script within the head tag of the html document*/      
           <script src="https://sdk.mercadopago.com/js/v2" strategy="beforeInteractive"/>
        </Head>

        <body>
          /*You can also add additional scripts here before loading other next.js scripts*/
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

Answer №2

I was able to solve this issue by utilizing the onLoad method within the Next/Script component. To resolve the problem, I moved the script inclusion to my own component and added the onLoad props while passing a function that executed my object instance after it had finished loading.

Below is the code I used:

const onload = () => {
     const controller = new Controller(props);
     setController(controller);
};
const pay = () => controller.load(props.disabled);
const attrs = {onClick: pay};
if (!controller || props.disabled) attrs.disabled = true;
return(
  <>
    <section className="mercadopago-checkout-pro-component">
        <div ref={refContainer} className="cho-container">
            <button  className="btn btn-secondary" {...attrs}>
                Pay
            </button>
        </div>
    </section>
    <Script src="https://sdk.mercadopago.com/js/v2" onLoad={onload}/>
   </>
);

Answer №3

Head over to the component where you require this particular script.

import Script from 'next/script'

const myComponent = () => {

const [razorpayInstance, setRazorpayInstance] = useState();

const handleLoadScript= () => {
var options: any = {
  "key": "myUniqueKey"
};
res = new Razorpay(options);
setRazorpayInstance(razorpay)

}

return( <> <Script id="onload-id" src="https://uniquecdn.com/slugs" onLoad={handleLoadScript} /> </> )}; 
export default myComponent;

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

Incorporating graphics into a React component

Currently exploring React JS and looking to dive into the practical side of things. Following a documentation tutorial that constructs a basic comment system. I've replicated the component structure outlined in the tutorial: PostBox PostList Pos ...

Can the image upload file size be customized or adjusted?

Recently, I've come across a standard input file code that looks like this: <Label class="custom-file-upload"> <input type="file" onChange={onDrop} /> Upload Photo </Label> I have been thinking about limiting the size of the ...

Save JSON data in an HTML document or vice versa

Hey there, the title of this post might seem a bit unclear but I couldn't think of another way to phrase it. So here's the dilemma: I have some data that is JSON encoded and stored in a .json file: {"foo":"bar", "bar":"foo", "far":"boo"} Additi ...

Combining multiple AngularJS expressions to form a URL within an interpolation statement

While this explanation may be lengthy, I appreciate your patience as I try to articulate the issue at hand. The error I'm currently encountering is as follows: Error: [$interpolate:noconcat] Error while interpolating: Strict Contextual Escaping disa ...

Executing an Amplifyjs GET request containing a request body

Is it possible to utilize GET requests with a message body using AmplifyJS? Specifically, I am curious about the process of achieving this functionality with AmplifyJS. While synthetic tests function properly (using Fiddler as my test client), I have enc ...

Adjusting hyperlinks placement based on window size changes using jQuery

On resizing the screen, I am moving the sub-nav links to the '#MoreList' It works well initially, but when the window is expanded again, the links remain in the #MoreList instead of going back to their original positions if there is enough space ...

The server remains unreachable despite multiple attempts to send data using Angular's $http

I am encountering an issue with triggering $http.post: app.controller('editPageController', function($scope, $routeParams, $http) { $scope.page = $routeParams.pageid; // retrieve page data from the server $http.get('/pages/&ap ...

Error: Unable to locate module '@/prismicio'

Recently, I embarked on a new project using Prismic + NextJS by following this template: https://vercel.com/templates/next.js/prismic-blog. Everything was set up as per the requirements, but unfortunately, I encountered the error message: Module not found: ...

Encountered an issue with JSON serialization while using getServerSideProps in Next.js and TypeScript to retrieve products from the Stripe Payments API

Encountered Issue on Localhost Error: The error occurred while serializing .products returned from getServerSideProps in "/". Reason: JSON serialization cannot be performed on undefined. Please use null or exclude this value. Code Sample import ...

Encountering Webpack errors causes nextJS build to fail on Vercel site deployment

I am currently facing an issue while trying to deploy my project on Vercel. Even though I have successfully deployed other projects before, this time the build process is failing. The error message indicates that it cannot find the Footer component, even ...

Attempting to resolve an error message with the help of JQuery

I need help figuring out how to clear an error icon when a user presses a key. ** EDIT - including the HTML code ** <input class="validate" type="text" data-type="string" id="address" /> <input class=" ...

Issue with accessing Scope value in AngularJS directive Scope

FIDDLE I've recently developed a directive that looks like this: return { restrict: 'EAC', scope: { statesActive: '=' }, link: function (scope, element, attrs) { var ...

Ways to showcase a JSON menu with a single level

I have a json file containing links to all the images in a specific folder, as shown below: ["http://img1.png","http://img2.png","http://img3.png","http://img4.png"] I would like to create a <ul> list using this data, but I'm not sure how to d ...

Creating a form with multiple checkboxes using Material-UI components where only a single checkbox can be selected

Creating a simple form using Material-UI with checkboxes to select one option and push data to the backend on submit is the goal. The Form component structure includes: multiple options represented by checkboxes only one checkbox can be selected at a time ...

Error in Material UI when using the select component

CustomComponent.js:98 UI Error: The value undefined provided for the selection is out of range. Please make sure to select a value that matches one of the available options or ''. The available options are: `All`, `Software Development`, `Qualit ...

Sending parameters with $location.path() in AngularJS

Having trouble creating a redirection call in the controller with a numerical parameter. Here is the code I've been using: $location.path('/tasklist/:$rootScope.job_id'); I have also attempted the following: $location.path("/tasklist/",$r ...

Send multiple values as arguments to a jQuery function

Beginner question ahead: I'm using the jquery function loadNewPicture() to upload pictures and the progress() function to track the percentage of the upload. Everything is functioning correctly. My query relates to the variables that can be passed t ...

What is the procedure for enabling S3 images or objects to be downloaded exclusively through website requests using pre-signed URLs?

I am facing a serious issue with my AWS S3 bucket setup. I have been using the aws-sdk javascript to upload files to the bucket and providing object links for downloading on my Next.js website. However, I recently realized that the bucket permissions are s ...

Why is the Slick Slider displaying previous and next buttons instead of icons?

I'm currently working on creating a slider using the slick slider. Everything seems to be functioning properly, but instead of displaying arrows on the sides, it's showing Previous and Next buttons stacked vertically on the left side. It appears ...

Use Javascript to display or conceal events on a fullcalendar interface

I am in the process of creating a religious calendar as part of a project that displays various events from major religions. Using the full calendar, I have included a "religion key" at the top of the calendar to differentiate between different faiths. My ...