I'm working on a simple javascript project (still learning) that requires an API. Among the requirements there is the use of webpack to hide the api key, but as far as I know it is not possible to hide the key from a front end application without a back end (which i cannot use it yet) ... am I missing something ?? Do I have to add some Node.js code??
Asked
Active
Viewed 1,575 times
0
-
1_"as far as I know it is not possible to hide the key from a front end application without a back end"_. Exactly – blex May 16 '21 at 10:45
-
You could keep the `API_KEY` outside your code within a `.env` file, although it would still be visible on `inspect` within the browser. Is this what you desire? – Tolumide May 16 '21 at 10:55
-
so i was right :( so what's the use of having webpack in a vanilla javascript application? – Andy May 16 '21 at 12:08
-
thanks @Tolumide, but i still need a back end for the env files right? – Andy May 16 '21 at 12:10
-
No, you don't. I would be creating an answer here as to how to use `.env` with webpack. – Tolumide May 16 '21 at 14:46
1 Answers
2
Within your webpack config, in the plugins
part add this:
// webpack.config.js
plugins: [
....
new webpack.DefinePlugin({
"process.env": {
API_KEY: JSON.stringify(process.env.API_KEY),
},
}),
]
create a .env
file, where you would add something like this:
// .env
API_KEY="thevalueOfTheAPIKey"
For the sake of security, your .env
file must be added to the .gitignore
file, you should also create a .env.sample
file, that others can use, the whole essence of the .env.sample
is to help others know how to recreate the .env
file locally, so for something like what we have above you would have:
// .env.sample
API_KEY=""
Within your project, whereever you would be using the environment variable e.g.
// index.js
require("dotenv").config();
const API_KEY = process.env.API_KEY;
You can read more about process.env
on the documentation here: https://nodejs.org/api/process.html#process_process_env

Tolumide
- 944
- 9
- 11