Environment-secret exposure through webpack DefinePlugin

Environment-secret exposure through webpack DefinePlugin

Description

Passing all of process.env to webpack’s DefinePlugin can put build-time secrets in browser JavaScript. Which values are emitted depends on how the code references them and how webpack optimizes it.

Potential impact

Anyone can read keys or tokens present in public bundles or source maps. Their permissions may allow data access or third-party API calls that increase charges. Exposure may also affect privacy obligations and customer trust.

Remediation

  • Separate environment files by purpose. Supply only public values to client builds in CI/CD and keep server secrets on the server.
  • Define approved keys individually with DefinePlugin or use an explicit allow-list such as EnvironmentPlugin(['NODE_ENV', 'PUBLIC_API_BASE']).

Examples

Before

javascript
// webpack.config.js (before)
const { DefinePlugin } = require("webpack");

// Replacing the entire environment may embed secrets in referencing code
const exposeAll = { "process.env": JSON.stringify(process.env) };

module.exports = {
  mode: "production",
  plugins: [new DefinePlugin(exposeAll)],
};

After

javascript
// webpack.config.js (after)
const { DefinePlugin, EnvironmentPlugin } = require("webpack");
require("dotenv").config();

// Expose only explicitly approved public keys, for example PUBLIC_ values
const PUBLIC_VARS = {
  "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
  "process.env.APP_VERSION": JSON.stringify(require("./package.json").version),
  "process.env.PUBLIC_API_BASE": JSON.stringify(process.env.PUBLIC_API_BASE),
};

module.exports = {
  mode: "production",
  plugins: [
    new DefinePlugin(PUBLIC_VARS),
    // Or explicitly allow only the required keys
    // new EnvironmentPlugin(['NODE_ENV', 'PUBLIC_API_BASE'])
  ],
};

The example defines NODE_ENV, APP_VERSION and PUBLIC_API_BASE. Confirm that each selected value is public, even if its name starts with PUBLIC_. Check the bundles and source maps produced by the client build for secrets.

References