Because dotenv relies on Node.js modules like fs and path, it cannot run directly in a browser. When using Webpack, you must provide polyfills or use a specialized plugin.
Option 1: Use dotenv-webpack (Recommended)
This plugin handles the injection of environment variables into your bundle automatically.
Option 2: Manual Webpack Configuration
If you are manually configuring Webpack, you must:
- Install
node-polyfill-webpack-plugin. - Use
webpack.DefinePlugin to map specific process.env keys to your bundle.
Note for React users: If using create-react-app, environment variables must be prefixed with REACT_APP_ to be accessible in the client-side code.
npm install node-polyfill-webpack-plugin
require('dotenv').config()
const path = require('path');
const webpack = require('webpack')
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
module.exports = {
mode: 'development',
entry: './src/index.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
plugins: [
new NodePolyfillPlugin(),
new webpack.DefinePlugin({
'process.env': {
HELLO: JSON.stringify(process.env.HELLO)
}
}),
]
};