Denny Lesmana
1 min readJul 8, 2022

--

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.

<script async type="text/javascript">const NR_APP_ID={config.env.nrAppId};</script>

The variable NR_APP_ID can be accessed via the external JS file _document.js.

Thanks for reading.

#NeverEndingImprovement

--

--

Denny Lesmana

Senior Full Stack Engineer @ Ajaib | Tech & Investment Enthusiast | twitter: https://twitter.com/Denny_lesmanaa