I am trying to put amp-analytics script into amp page generated from Next.js, but dangerouslySetInnerHTML breaks JSON config because of & character.
Here is the code:
<amp-analytics id='analytics1' type='googleanalytics'>
<script type='application/json' dangerouslySetInnerHTML={{ __html: `
{
"vars": {
"account": "XX-XXXXXXXX-X"
},
"requests": {
"experiment": "\${pageview}&xid=\${xid}&xvar=\${xvar}"
}
}
` }} />
</amp-analytics>
As you can see the & character was converted to \u0026 and now amp-analytics tag doesn't work.
I also tried this:
<amp-analytics id='analytics1' type='googleanalytics'>
<script type='application/json' dangerouslySetInnerHTML={{ __html: `
{
"vars": {
"account": "XX-XXXXXXXX-X"
},
"requests": {
"experiment": "${JSON.stringify('${pageview}&xid=${xid}&xvar=${xvar}')}"
}
}
` }} />
</amp-analytics>
But got not valid JSON (with right & symbol)

Any ideas on how can I solve this?
As It turned out it happens because of AMP Optimizer in Next.js — github.com/ampproject/amp-toolbox/pull/649 And now I have to find a solution for that case

You don't need to use
dangerouslySetInnerHTML, given that all you want to do is set the text content.dangerouslySetInnerHTMLis required only if you need to parse HTML into DOM nodes.You can set the text content like this:
If you do it this way, React is smart enough to know that HTML entities aren't required in
scripttags, so those&s won't be escaped (unlike if it was a normal HTML element such asdiv).You can verify that like this (demo):