(Next.js 12/13) Does next/script support dynamically updating inline scripts?

497 Views Asked by At

next/script supports inline scripts.

I am trying to use a 3rd party script and I need to update some part of the script based on changes to a state in my page.

// ... rest of component

const [thisVariable, setThisVariable] = useState('default value');

// ... return block
<Script ...props />
  {`some 3rd party script tag where ${thisVariable} needs to change with component state`}
</Script>

This apparently does not work, it will only render the default value into the generated <script> tag.

Does anyone know if this is possible or supported by NextJS? I have a possible workaround using a useEffect to target the generated script (I know the id) and modify the inner text with some clever regex, but that feels dirty and over-engineered.

Some other considerations: This 3rd party does not expose an API. This inline script generates a url that gets inserted as the src for another script tag. I may try to just target that tag and dynamically create that url.

Thanks!

Edit:

I took a dive into the next/script source code, and in fact it looks like the component is wired to only append the <script> tag once, at this useEffect here: https://github.com/vercel/next.js/blob/canary/packages/next/src/client/script.tsx#L228

If there's any thoughts, I'd love to hear them but consider this question resolved: No it's not supported to dynamically update inline scripts in the Script component.

1

There are 1 best solutions below

0
Michael Nguyen On

I took a dive into the next/script source code, and in fact it looks like the component is wired to only append the tag once, at this useEffect here: https://github.com/vercel/next.js/blob/canary/packages/next/src/client/script.tsx#L228