#Using data- attributes on next/script

1 messages · Page 1 of 1 (latest)

silver sage
#

How could I set "data-key" attribute to <Script/> element from next/script? Or should I use normal <script> element?

balmy lavaBOT
#

Hi @silver sage. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

You can indeed set custom data attributes like "data-key" on the <Script/> component from next/script. The Next.js documentation explicitly mentions that additional attributes, including custom data attributes, can be used with the Script component.

Here's how you can do it:

import Script from 'next/script'

export default function Page() {
  return (
    <>
      <Script
        src="<https://example.com/script.js">
        id="example-script"
        data-key="your-value-here"
      />
    </>
  )
}

According to the Next.js documentation on Script Optimization, any additional attributes you include will be automatically forwarded to the final, optimized <script> element in the HTML.

The documentation states:

There are many DOM attributes that can be assigned to a <script> element that are not used by the Script component, like nonce or custom data attributes. Including any additional attributes will automatically forward it to the final, optimized <script> element that is included in the HTML.

Therefore, you should use the <Script/> component from next/script rather than a normal <script> element, as it provides additional optimization features while still allowing you to set custom attributes.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: