Relic Solution: Browser snippet using dangerouslySetInnerHtml in React

I just wanted to share a solution that I found on GitHub for adding the browser snippet to page via the dangerouslySetInnerHtml attribute in React, just in case someone is looking for an example implementation in the future.

Note: dangerouslySetInnerHtml was formerly called the innerHTML attribute but was changed just to remind users that:

setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack

In this case, the html you are setting is the New Relic browser agent copy paste script, so the risk should be mitigated.

The solution was found on this GitHub issue:

credit to

  1. Create a new Browser project:

  2. Select “Pro + SPA” and Copy/Pase code, save the code into a text file
    remove the script tags from the file and replace chars “” with “\”. (escape the escape characters)

  3. Create a new react Component NewRelicSnippet .tsx: and add the escaped script string into it.

     // Copy-Paste code use Pro + SPA  on newrelic
     const snippet = `
     export const NewRelicSnippet = () => {
         return <script type="text/javascript" dangerouslySetInnerHTML={{ __html: snippet}} />
  4. Add this component into: _app.tsx (or jsx)

         return (
                     <NewRelicSnippet />
                 {/* ... */}

This solution has worked in a use case that I was working on with a customer, so wanted to make sure it was easy to find on the community!