apiKey returning undefined using browserify & dotenv

36 Views Asked by At

Hoping someone might be able to help me to resolve the below.

I am trying to utilise .env to store my API key. I have tried several methods but have been unable to return/ use my API key as of yet.

So far I have tried the following:

  1. Using dotnev I could console.log the API key in the terminal but then hit other challenges when opening my code in a browser. I could not seem to resolve this using square brackets or similar Screenshot of error

In HTML `<script src="./node_modules/requirejs/require.js"

`

In my JS file require("dotenv").config(); const apiKey = process.env.API_KEY; console.log(apiKey);

In .env API_KEY = "123ABC"

  1. Adding browserify to bundle

In HTML <script defer src="./bundle.js"></script>

In my JS file require("dotenv").config(); const apiKey = process.env.API_KEY; console.log(apiKey);

In .env API_KEY = "123ABC"

I'm then running browserify index.js > bundle.js in the VS Code integrated terminal.

The console.log(apiKey) results in undefined.

Would anyone be able to suggest any workarounds? I have seen webpack in some solutions but for this project am keen not to use webpack.

For clarity, I am copying the path of my index.html and pasting into the browser, not using the VS Code Live Server add on (this caused other issues around require not being defined)

Thanks so much!

1

There are 1 best solutions below

0
JustinL On

Plese try in .env

API_KEY = 123ABC

This should be it. Also please do not use console.log(API_KEY) with a real value at your website.