简体   繁体   中英

How to use webpack in Javascript to hide api key

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??

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 eg

// 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM