Dynamically add environment variable to an external js script with NextJS
I recently started building a web app using NextJS for internal use and ran into a problem. I’d like to enable New Relic’s external JS script for monitoring purposes, but I’d like to do so dynamically, so that the app id is obtained from the.env file at each stage (Development, UAT, and Production).
Here’s how I solved that problem without a library.
I saved the script generated by newrelic in public/js/newrelic.js. We create a new config environment object with nrAppId in next.config.js. I added several external JS scripts, such as the Google API font and the New Relic script, using a custom document. We only need to call the variable from next.config.js in the document.
The variable NR_APP_ID can be accessed via the external JS file _document.js.
Thanks for reading.
Advanced Features: Custom `Document` | Next.js
A custom Document can update the and tags used to render a Page. This file is only rendered on the server, so event…