Rendering dynamic content in a script tag in Astro JS

I’m trying to render some dynamic content in a script tag inside a .astro file.

I currently have:

---
import getData from '../../helpers/getData.js'

const data = getData({
      // some data
    })

const stringifyData = JSON.stringify(data)
---

<html lang="en">
  
{stringifyData && (
  <script type="application/ld+json">
    {stringifyData}
  </script>
)}
</html>

but its rendering the below in the html

<script type="application/ld+json">
    {stringifyData}
  </script>

Any help would be much appreciated

You can use the following

---
const data = getData()
---
<html>
  <head>
    {data && <script type="application/ld+json" set:html={JSON.stringify(data)}></script>}
  </head>
</html>

Leave a Comment