Immediate Fix
The “ReferenceError: process is not defined” usually occurs because you are trying to use Node.js-specific code (like process.env) in a browser environment. Browsers do not have a global process object.
To fix this immediately in a React or Vanilla JS project, add this script tag inside the <head> of your index.html file before any other scripts:
<script>
window.process = {
env: { NODE_ENV: 'development' },
version: '',
nextTick: (cb) => setTimeout(cb, 0)
};
</script>
If you are using Vite, you can fix this by adding a define property to your vite.config.js file:
export default defineConfig({
define: {
'process.env': {}
}
})
Technical Explanation
The process object is a global variable in Node.js that provides information about the current system environment. It is widely used for accessing environment variables and controlling the lifecycle of a script.
Modern frontend build tools like Webpack 5 and Vite no longer automatically include polyfills for Node.js globals. This design choice reduces bundle size but causes errors when libraries rely on the legacy process object.
When the browser engine encounters process.env and cannot find a declaration for process, it throws a ReferenceError and halts script execution.
[
]
Alternative Methods
Depending on your build tool and project requirements, you may need a more robust solution than a simple script tag injection.
Method 1: Webpack ProvidePlugin
If you are using Webpack, you can use the ProvidePlugin to automatically load the process polyfill whenever the variable is encountered.
const webpack = require('webpack');
module.exports = {
plugins: [
new webpack.ProvidePlugin({
process: 'process/browser',
}),
],
};
Method 2: Use Environment-Specific Syntax
If you are writing modern ESM (ECMAScript Modules), you should transition away from Node-specific globals entirely.
| Environment | Correct Syntax |
|---|---|
| Vite | import.meta.env.VITE_VAR |
| Create React App | process.env.REACT_APP_VAR |
| Next.js | process.env.NEXT_PUBLIC_VAR |
Method 3: Install the Process Package
In some cases, you might need the full functionality of the process shim. You can install it via npm and import it manually.
npm install process
Then, add this to the very top of your entry file (e.g., main.js or index.js):
import process from 'process';
window.process = process;