Search code examples
reactjstypescriptnext.jscloudinarynext.js13

Next.js build failed - function from next/script not found


I'm building a CMS using next.js and one of the features is media management using Cloudinary. I've managed to include the Cloudinary Media Library widget with the use of next/script and it works perfectly in development but encountered an error and is refusing to build. I am using Next.JS with TypeScript

My Script component from next/script

 <Script
  id="cloudinary"
  defer
  src="https://media-library.cloudinary.com/global/all.js"
  onReady={function () {
    widgetRef.current = cloudinary.createMediaLibrary(
      {
        cloud_name: "<cloud name here>",
        api_key: "<api key here>",
        multiple: false,
      },
      {
        insertHandler: (data) => {
        const selectedImage = { ...data.assets[0] };
        form.setFieldValue("image", selectedImage.url);
        },
      }
    );

    setWidgetReady(true);

  }}></Script>

and later the widget is called by user interaction with a button

<Button
   onClick={() => widgetRef.current.show()}
   loading={!widgetReady}
   leftIcon={<FontAwesomeIcon icon={faImage} />}
>
Select/Upload Image
</Button>

in dev, the widget opens with no issues

Cloudinary Media Library Widget Screenshot

as I'm building for deployment here's the error

Type error: Cannot find name 'cloudinary'.

  207 |             src="https://media-library.cloudinary.com/global/all.js"
  208 |             onReady={function () {
> 209 |               widgetRef.current = cloudinary.createMediaLibrary(
      |                                   ^
  210 |                 {
  211 |                   cloud_name: "<cloud name here>",
  212 |                   api_key: "<api key here>",
error Command failed with exit code 1.

I'm not sure where to even begin debugging this. Any help is appreciated. Thanks.


Solution

  • Try adding an initialization to Cloudinary:

            var cld = cloudinary.Cloudinary.new({ cloud_name: 'my_cloud' });
            widgetRef.current = cld.createMediaLibrary(
                     {
                      cloud_name: "<cloud name here>",
                      api_key: "<api key here>",
                      .......