Open source

dotenv-webpack

Bring .env configuration into webpack and expose only the environment variables your code explicitly references.

Set up dotenv-webpack

Install the plugin as a build dependency.

npm install --save-dev dotenv-webpack

Add a public build setting to .env in the project root.

PUBLIC_API_ORIGIN=https://api.example.com

Add the plugin to webpack.config.cjs, alongside any plugins already in use.

const Dotenv = require('dotenv-webpack')

module.exports = {
  plugins: [new Dotenv()],
}

Reference the key directly in application code. The plugin substitutes its value when webpack builds the bundle.

export const apiOrigin = process.env.PUBLIC_API_ORIGIN

Build-time values and browser bundles

Rebuild the application after changing .env. The bundle contains the substituted value and does not read .env after it reaches the browser. Use a direct reference such as process.env.PUBLIC_API_ORIGIN because destructuring process.env is unsupported.

Treat every value referenced by browser code as public. API keys that grant privileged access, database passwords, and other credentials belong in the server runtime.

Shared fallbacks

Set defaults: true in the plugin options to load fallback values from .env.defaults. For a Node.js application that loads configuration at runtime, see the dotenv-defaults setup guide.