Expand my Community achievements bar.

SOLVED

Next Js + Marketo Form Integration

Avatar

Level 1

Hey! I'm having a weird problem with a Marketo form in my Next.js app. The form works perfectly fine in my local environment, but in production it's super inconsistent.

The main issue is that when users first load the page, the form doesn't show up at all. Sometimes if you refresh the page (shift+F5) the form appears, but it's really random - sometimes it works, sometimes it doesn't.

Here's what I know:

  • Works 100% of the time in local development
  • In production, initial page load = no form
  • Sometimes works after a hard refresh
  • The Marketo script loads successfully (I can see it in the network tab)
  • I'm getting "Error loading form: error" in the console
  • Using Next.js Script component to load Marketo's script
  • Already tried different loading strategies (afterInteractive, lazyOnload)

Looking at the logs, it seems like there might be a timing issue between when the Marketo script loads and when it tries to initialize the form, but I can't figure out exactly what's going wrong.

Has anyone run into similar issues with Marketo forms in Next.js? Any suggestions would be super helpful!

Here's my current implementation:

 

 

import { useRef, useState, useEffect } from "react";
import { bool } from "prop-types";
import Link from "next/link";
import Script from 'next/script';
import styles from "./signupscript.module.scss";

export default function SignUpScript({ greyBg, borderBottom }) {
  const formRef = useRef(null);
  const formInstanceRef = useRef(null);
  const [scriptLoaded, setScriptLoaded] = useState(false);
  const [scriptError, setScriptError] = useState(null);
  const [loadAttempts, setLoadAttempts] = useState(0);

  const loadForm = () => {
    console.log("8. Attempting to load form - Attempt #", loadAttempts + 1);
    
    if (window.MktoForms2 && formRef.current && !formInstanceRef.current) {
      try {
        console.log("9. Starting form load with params:", {
          baseUrl: "https://go.company.com",
          munchkinId: "XXX-YYY-ZZZ",
          formId: 1234,
          formElement: formRef.current
        });

        formInstanceRef.current = window.MktoForms2.loadForm(
          "https://go.company.com",
          "XXX-YYY-ZZZ",
          1234,
          (form) => {
            console.log("10. Form load callback executed", form);
            
            if (form) {
              console.log("10a. Form instance created successfully");
              form.onSuccess((values, followUpUrl) => {
                console.log("11. Form success:", values);
                return false;
              });
            } else {
              console.error("10b. Form instance is null");
              throw new Error("Form instance is null");
            }
          }
        );

        console.log("12. loadForm call completed");
      } catch (error) {
        console.error("13. Error in loadForm:", error);
        if (loadAttempts < 3) {
          console.log("13a. Scheduling retry...");
          setTimeout(() => {
            setLoadAttempts(prev => prev + 1);
          }, 1000);
        } else {
          setScriptError(error);
        }
      }
    } else {
      console.log("14. Conditions not met:", {
        hasMktoForms2: !!window.MktoForms2,
        hasFormRef: !!formRef.current,
        hasInstance: !!formInstanceRef.current
      });
    }
  };

  useEffect(() => {
    if (scriptLoaded && loadAttempts < 3) {
      console.log("15. Scheduling form load with delay");
      const timer = setTimeout(loadForm, 1000);
      return () => clearTimeout(timer);
    }
  }, [scriptLoaded, loadAttempts]);

  const handleScriptLoad = () => {
    console.log("--- DEBUG LOGS START ---");
    console.log("1. Script onLoad event triggered");
    console.log("2. Window object available?", typeof window !== 'undefined');
    console.log("3. FormRef exists?", !!formRef.current);
    console.log("4. MktoForms2 available?", !!window.MktoForms2);
    setScriptLoaded(true);
  };

  const handleScriptError = (error) => {
    console.error("16. Script failed to load:", error);
    setScriptError(error);
  };

  console.log("17. Component rendering with states:", {
    scriptLoaded,
    hasError: !!scriptError,
    formRefExists: !!formRef.current,
    formInstanceExists: !!formInstanceRef.current,
    attempts: loadAttempts
  });


  return (
    <section
      id="signup"
      className={styles.signup}
      style={{
        backgroundColor: greyBg ? "#f3f3f3" : "#f3f3f3",
        borderBottom: borderBottom ? "59px solid #abc448" : "none",
      }}
    >
      <Script
        src="https://go.bauschhealth.com/js/forms2/js/forms2.min.js"
        strategy="afterInteractive"
        onLoad={handleScriptLoad}
        onError={handleScriptError}
      />
      <div className="container">
        <div className={styles.form}>
          <div className={styles.form__wrapper}>
            <div className={styles.form__sectionOne}>
              <h2 className={styles.form__h2}>
                Sign up now to receive bowel
                prep reminders, tips, and&nbsp;more
              </h2>
              <div className={styles.form__info}>
                <img
                  src="/images/comps/signup/phone-texting-icon.svg"
                  alt="phone"
                  className={styles.form__iconPhone}
                />
                <div className={styles.form__ul}>
                  <p className={styles.form__li}>
                    <img
                      src="/images/comps/signup/pink checkmark.svg"
                      alt="checkmark"
                    />
                    <span>Dosing notifications to keep you on track</span>
                  </p>
                  <p className={styles.form__li}>
                    <img
                      src="/images/comps/signup/pink checkmark.svg"
                      alt="checkmark"
                    />
                    <span>Helpful tips to ease the prep process</span>
                  </p>
                  <p className={styles.form__li}>
                    <img
                      src="/images/comps/signup/pink checkmark.svg"
                      alt="checkmark"
                    />
                    <span>
                      Access to additional PLENVU® resources, including co-pay
                      savings
                    </span>
                  </p>
                </div>
              </div>
            </div>
            <div className={styles.form__inputs}>
              <div className={styles.formContainer}>
                <form id="mktoForm_4351" ref={formRef}></form>
              </div>
            </div>
          </div>
        </div>
        <p className={styles.signup__pDisclaimer}>
          <strong>
            Disclaimer: This dosing guide is for educational purposes only and
            is not intended to take the place of your healthcare provider.
          </strong>
        </p>
        <p className={styles.additional_info}>
          <strong>
            For additional information, see the full{" "}
            <Link 
              href="https://shared.salix.com/globalassets/pi/plenvu-pi.pdf#page=10"
              target="_blank"
              rel="noopener noreferrer"
            >
              Instructions for Use
            </Link>
          </strong>
        </p>
      </div>
    </section>
  );
}

SignUpScript.propTypes = {
  greyBg: bool,
  borderBottom: bool,
};

 

 

Please helperino :C

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Hi @Mauro_AlejandroUr 

Please move this thread to dedicated Marketo Community https://nation.marketo.com/ 



Arun Patidar

View solution in original post

2 Replies

Avatar

Correct answer by
Community Advisor

Hi @Mauro_AlejandroUr 

Please move this thread to dedicated Marketo Community https://nation.marketo.com/ 



Arun Patidar

Avatar

Community Advisor

Hi @Mauro_AlejandroUr ,

Loading script is where things can get a little tricky. I'd suggest to create a logic that handles adding the Marketo script to the page, and removes all default styling from the Marketo form.

 

  • A hidden Marketo form with all styles removed.
  • A Logic that loads the script into the page.
  • A real form that end users will see and use.

You can follow below link, though this deal with React but might be useful:
https://www.paulie.dev/posts/2022/12/how-to-create-custom-marketo-forms-with-react/

 

-Tarun