No articles found
Try different keywords or browse our categories
Fix: process is not defined error in React Vite - Complete Solution Guide
Learn how to fix the 'process is not defined' error in React Vite projects. This guide covers environment variables, Node.js compatibility, and best practices for Vite configuration.
The ‘process is not defined’ error is a common issue that React developers encounter when working with Vite projects. This error occurs because Vite, unlike Create-React-App or Webpack, doesn’t automatically provide Node.js environment variables like process.env to the browser environment. The process object is a Node.js global that doesn’t exist in browsers.
This comprehensive guide explains what causes this error, why it happens, and provides multiple solutions to fix it in your React Vite projects with clean code examples and directory structure.
What is the process is not defined Error?
The process is not defined error occurs when your React application tries to access the process object, which is a Node.js global variable that doesn’t exist in the browser environment. Vite doesn’t automatically polyfill Node.js globals like process.env, unlike other build tools.
Common Error Messages:
ReferenceError: process is not definedprocess is not definedCannot read property 'env' of undefined
Understanding the Problem
In traditional Node.js environments, process is a global object that provides information about the current process and environment variables. However, in browser environments:
- No Node.js globals: Browsers don’t have Node.js globals like
process - Vite doesn’t polyfill: Vite doesn’t automatically provide Node.js globals
- Environment variables: Accessing
process.envfails in the browser - Third-party libraries: Some libraries expect Node.js globals
Typical React Vite Project Structure:
my-vite-app/
├── package.json
├── vite.config.js
├── index.html
├── src/
│ ├── main.jsx
│ ├── App.jsx
│ └── components/
│ └── MyComponent.jsx
├── public/
└── .env
Solution 1: Use Vite’s Environment Variables (Recommended)
Vite provides its own way to handle environment variables using import.meta.env.
❌ Before (Causing Error):
// src/components/MyComponent.jsx
function MyComponent() {
// ❌ This will cause "process is not defined" error
const isDevelopment = process.env.NODE_ENV === 'development';
const apiUrl = process.env.REACT_APP_API_URL;
return (
<div>
<p>Environment: {isDevelopment ? 'Development' : 'Production'}</p>
<p>API URL: {apiUrl}</p>
</div>
);
}
✅ After (Fixed):
// src/components/MyComponent.jsx
function MyComponent() {
// ✅ Use Vite's environment variables
const isDevelopment = import.meta.env.DEV;
const apiUrl = import.meta.env.VITE_API_URL;
return (
<div>
<p>Environment: {isDevelopment ? 'Development' : 'Production'}</p>
<p>API URL: {apiUrl}</p>
</div>
);
}
Environment File (.env):
# .env
VITE_API_URL=https://api.example.com
VITE_APP_NAME=My Vite App
Solution 2: Configure Vite to Define Process
Add process polyfill to your Vite configuration.
vite.config.js:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
define: {
global: 'globalThis',
'process.env': {}
}
})
Install Required Packages:
npm install --save-dev @vitejs/plugin-react
Solution 3: Use @vitejs/plugin-legacy for Process Polyfill
For projects that heavily rely on Node.js globals.
vite.config.js:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'
export default defineConfig({
plugins: [react()],
define: {
global: 'globalThis'
},
optimizeDeps: {
esbuildOptions: {
define: {
global: 'globalThis'
},
plugins: [
NodeGlobalsPolyfillPlugin({
process: true,
buffer: true
})
]
}
}
})
Install Required Packages:
npm install --save-dev @esbuild-plugins/node-globals-polyfill
Solution 4: Create a Process Polyfill
Create a custom process polyfill for your application.
src/polyfills/process.js:
// src/polyfills/process.js
if (typeof process === 'undefined') {
window.process = {
env: {
NODE_ENV: import.meta.env.MODE || 'development',
...Object.keys(import.meta.env).reduce((acc, key) => {
if (key.startsWith('VITE_')) {
acc[key] = import.meta.env[key];
}
return acc;
}, {})
}
};
}
Import in main.jsx:
// src/main.jsx
import './polyfills/process'; // Import polyfill first
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)
Solution 5: Use Environment-Specific Configuration
Create different configurations for different environments.
vite.config.js:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig(({ mode }) => {
const config = {
plugins: [react()],
define: {
global: 'globalThis'
}
};
if (mode === 'development') {
config.define = {
...config.define,
'process.env': {
NODE_ENV: 'development',
...process.env
}
};
} else {
config.define = {
...config.define,
'process.env': {
NODE_ENV: 'production'
}
};
}
return config;
});
Solution 6: Handle Third-Party Library Issues
For third-party libraries that expect Node.js globals.
vite.config.js:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'
export default defineConfig({
plugins: [react()],
define: {
global: 'globalThis'
},
optimizeDeps: {
esbuildOptions: {
define: {
global: 'globalThis'
},
plugins: [
NodeGlobalsPolyfillPlugin({
process: true,
buffer: true,
util: true
})
]
}
},
resolve: {
alias: {
process: 'process/browser',
buffer: 'buffer'
}
}
})
Install Required Packages:
npm install --save-dev @esbuild-plugins/node-globals-polyfill process buffer
Solution 7: Create a Custom Hook for Environment Variables
Create a custom hook to handle environment variables safely.
src/hooks/useEnv.js:
// src/hooks/useEnv.js
import { useMemo } from 'react';
export function useEnv() {
return useMemo(() => {
return {
isDevelopment: import.meta.env.DEV,
isProduction: import.meta.env.PROD,
apiUrl: import.meta.env.VITE_API_URL,
appName: import.meta.env.VITE_APP_NAME,
// Add other environment variables as needed
};
}, []);
}
// Usage in component
function MyComponent() {
const env = useEnv();
return (
<div>
<p>Environment: {env.isDevelopment ? 'Development' : 'Production'}</p>
<p>API URL: {env.apiUrl}</p>
</div>
);
}
Solution 8: Use a Configuration Service
Create a centralized configuration service.
src/config/index.js:
// src/config/index.js
const config = {
apiUrl: import.meta.env.VITE_API_URL || 'http://localhost:3000',
appName: import.meta.env.VITE_APP_NAME || 'My App',
isDevelopment: import.meta.env.DEV,
isProduction: import.meta.env.PROD,
// Add other configuration values
};
export default config;
Usage:
// src/components/MyComponent.jsx
import config from '../config';
function MyComponent() {
return (
<div>
<p>App Name: {config.appName}</p>
<p>API URL: {config.apiUrl}</p>
</div>
);
}
Complete Project Structure After Fix
my-vite-app/
├── package.json
├── vite.config.js
├── index.html
├── .env
├── .env.development
├── .env.production
├── src/
│ ├── main.jsx
│ ├── App.jsx
│ ├── config/
│ │ └── index.js
│ ├── hooks/
│ │ └── useEnv.js
│ ├── polyfills/
│ │ └── process.js
│ └── components/
│ └── MyComponent.jsx
└── public/
Working Code Examples
Complete Vite Configuration:
// vite.config.js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
define: {
global: 'globalThis',
'process.env': {
NODE_ENV: process.env.NODE_ENV || 'development',
// Add other environment variables as needed
}
},
server: {
port: 3000,
open: true
}
})
Environment Variables Usage:
// src/App.jsx
import { useState, useEffect } from 'react';
function App() {
const [apiData, setApiData] = useState(null);
useEffect(() => {
const fetchApiData = async () => {
try {
// Use Vite's environment variables
const response = await fetch(import.meta.env.VITE_API_URL + '/data');
const data = await response.json();
setApiData(data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchApiData();
}, []);
return (
<div className="App">
<h1>{import.meta.env.VITE_APP_NAME || 'My Vite App'}</h1>
<p>Environment: {import.meta.env.MODE}</p>
<p>Development: {import.meta.env.DEV ? 'Yes' : 'No'}</p>
{apiData && <pre>{JSON.stringify(apiData, null, 2)}</pre>}
</div>
);
}
export default App;
Environment Files:
# .env (default)
VITE_APP_NAME=My Vite App
VITE_API_URL=https://api.example.com
# .env.development
VITE_API_URL=http://localhost:3000
# .env.production
VITE_API_URL=https://api.production.com
Best Practices for Environment Variables in Vite
1. Use VITE_ Prefix
// ✅ Correct - Vite only exposes variables with VITE_ prefix
const apiUrl = import.meta.env.VITE_API_URL;
// ❌ Wrong - won't be available in browser
const apiUrl = import.meta.env.REACT_APP_API_URL;
2. Provide Default Values
// ✅ Provide fallbacks
const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:3000';
3. Validate Environment Variables
// ✅ Validate required variables
if (!import.meta.env.VITE_API_URL) {
console.warn('VITE_API_URL is not defined');
}
4. Group Related Variables
// ✅ Organize related variables
const apiConfig = {
baseUrl: import.meta.env.VITE_API_URL,
timeout: import.meta.env.VITE_API_TIMEOUT || 5000,
retries: import.meta.env.VITE_API_RETRIES || 3
};
Debugging Steps
Step 1: Check Environment Variables
# Verify environment variables are loaded
console.log('Environment:', import.meta.env);
console.log('Mode:', import.meta.env.MODE);
console.log('Development:', import.meta.env.DEV);
Step 2: Verify Vite Configuration
// Check vite.config.js for define configuration
export default defineConfig({
define: {
global: 'globalThis',
'process.env': {}
}
})
Step 3: Test Environment File
# Create .env file with VITE_ prefixed variables
VITE_TEST_VAR=hello
Step 4: Verify in Component
// Test in component
console.log('Test variable:', import.meta.env.VITE_TEST_VAR);
Common Mistakes to Avoid
1. Using process.env Instead of import.meta.env
// ❌ Don't do this
const apiUrl = process.env.REACT_APP_API_URL;
// ✅ Do this instead
const apiUrl = import.meta.env.VITE_API_URL;
2. Forgetting VITE_ Prefix
// ❌ Wrong - won't be available
const apiUrl = import.meta.env.API_URL;
// ✅ Correct
const apiUrl = import.meta.env.VITE_API_URL;
3. Not Installing Required Dependencies
# ❌ Missing dependencies can cause issues
npm install @vitejs/plugin-react
# For process polyfill
npm install process buffer
Performance Considerations
1. Minimize Environment Variables
// ✅ Only include necessary variables
const config = {
apiUrl: import.meta.env.VITE_API_URL,
// Don't include unnecessary variables
};
2. Tree Shaking
// ✅ Use destructuring to enable tree shaking
const { VITE_API_URL, VITE_APP_NAME } = import.meta.env;
Security Considerations
1. Don’t Expose Sensitive Data
// ❌ Don't expose secrets
VITE_API_SECRET=your-secret-key
// ✅ Keep secrets server-side
VITE_API_URL=https://api.example.com
2. Validate Input
// ✅ Validate environment variables
const apiUrl = import.meta.env.VITE_API_URL;
if (!apiUrl || !apiUrl.startsWith('https://')) {
throw new Error('Invalid API URL');
}
Testing Environment Variables
1. Development Server
# Test with development server
npm run dev
2. Production Build
# Test production build
npm run build
npm run preview
3. Unit Tests
// Mock environment variables in tests
import.meta.env.VITE_API_URL = 'http://localhost:3000';
Alternative Solutions
1. Use Create-React-App Instead
# CRA handles process.env automatically
npx create-react-app my-app
2. Use Next.js
# Next.js has built-in environment variable support
npx create-next-app my-app
3. Custom Build Script
// Create custom script to handle process
const process = {
env: {
NODE_ENV: 'development',
...Object.keys(process.env).reduce((acc, key) => {
if (key.startsWith('VITE_')) {
acc[key] = process.env[key];
}
return acc;
}, {})
}
};
Migration Checklist
- Replace all
process.envreferences withimport.meta.env - Add
VITE_prefix to environment variables - Update Vite configuration with proper define settings
- Test development and production builds
- Verify all environment variables work correctly
- Update documentation for team members
Conclusion
The ‘process is not defined’ error in React Vite projects occurs because Vite doesn’t automatically provide Node.js globals to the browser environment. By using Vite’s native environment variable system (import.meta.env), configuring proper polyfills, or creating custom solutions, you can resolve this error and maintain a smooth development experience.
The key is to embrace Vite’s approach to environment variables rather than trying to replicate Node.js behavior. With proper configuration and the solutions provided in this guide, your React Vite applications will handle environment variables correctly and avoid the process is not defined error.
Remember to always use the VITE_ prefix for environment variables you want to access in the browser, keep sensitive information server-side, and test thoroughly after implementing changes.
Related Articles
Fix: Invalid React hook call. Hooks can only be called inside of the body of a function component
Learn how to fix the 'Invalid hook call' error in React. This guide covers all causes, solutions, and best practices for proper React hook usage with step-by-step examples.
Fix: Module not found: Can't resolve 'react/jsx-runtime' - Complete Solution Guide
Learn how to fix the 'Module not found: Can't resolve react/jsx-runtime' error in React projects. This guide covers causes, solutions, and prevention strategies with step-by-step instructions.
Fix: npm ERR! ERESOLVE unable to resolve dependency tree in React Projects
Learn how to fix the 'npm ERR! ERESOLVE unable to resolve dependency tree' error in React projects. This guide covers causes, solutions, and best practices for dependency management.