New Relic Browser with Environment Variables

We would like to deploy New Relic Browser to some SPAs using the copy and paste implementation method. However, we want to be able to vary the applicationID and licenseKey per environment and so rather than pasting the script directly onto the page we’re fetching these values from environment variables and adding them to the script dynamically. The populated script is saved to a javascript file and we add a reference to this file towards the bottom of the <body> tag.

This approach seems to yield inconsistent results. For example, for one application we are seeing some transactions appearing in the dashboard, though not all traces are showing up:

For another application we aren’t seeing any data at all:

I’m aware that the documentation states that the script should be added to the bottom of the <head> tag but this isn’t ideal given that we need to be able to modify the script dynamically.

Do we need to move our scripts into the page <head>? Is there an alternative approach for working with environment variables and environment specific IDs?

Hey @rpurcell,

Placing the Browser JS snippet in the <head> tag is required for the proper instrumentation of an application.

There are a few reasons for this requirement, the first being the inline HEAD placement ensures the instrumentation code is loaded before all other scripts so that wrapping will occur when other libraries are registered. The second is, inline code placement also eliminates the network round trips caused by externally referenced scripts.

Aside from having an APM agent do the heavy lifting with an auto-injected snippet, there isn’t an alternative approach to working with environment specific IDs at this point.

Let us know if you have any questions about this.


1 Like

We are experiencing a similar issue. Our NR script file is loaded with a script tag in head but the license key and application id are set after application setting for that environment are loaded. This doesn’t work most of the times probably because of timing!? Is there a way to re-init the NR library?

Hi @Catalin.Tomescu,

I’d need to access the application to see exactly what’s going on. But, yes, if you are not getting the identifying values (license key and application ID) in there before the report is sent, we’re not going to be able to correctly process your application’s data.

There’s not a way to reinitialize the agent, the better approach is to change how/when you’re setting the data. This is going to vary based on your use case, but here’s an example I refer to frequently where a customer came up with a pretty good solution for their application using Angular and Webpack:


@Catalin.Tomescu - Let us know if Holly’s message was helpful - or, is there anything further we can help with?

@RyanVeitch - we switched to using the CI/CD pipeline to set the app ID and NR key in the JS file at deploy time.


Thanks for confirming @Catalin.Tomescu :smiley: