Logo

dev-resources.site

for different kinds of informations.

Uncaught ReferenceError: process is not defined

Published at
8/20/2023
Categories
vite
react
environment
variables
Author
boostup
Categories
4 categories in total
vite
open
react
open
environment
open
variables
open
Author
7 person written this
boostup
open
Uncaught ReferenceError: process is not defined

How to solve the following error ?

Uncaught ReferenceError: process is not defined
Enter fullscreen mode Exit fullscreen mode

First, this happens when, in your Vite/React project, you add a code equivalent to the following:

const someValue = process.env.SOME_KEY;
Enter fullscreen mode Exit fullscreen mode

In other words, you're simply trying to read a value from your .env file, which includes assignments similar to this:

SOME_KEY=A_VERY_IMPORTANT_VALUE_YOU_NEED
Enter fullscreen mode Exit fullscreen mode

Solving this issue

  1. Open the vite.config.ts file

  2. Add loadEnv in your imports:
    import { defineConfig, loadEnv } from 'vite'

  3. Add an env const assigment:
    const env = loadEnv(mode, process.cwd(), '');

  4. add a define object at the same level than the plugins array:

return {
    define: {
      'process.env.SOME_KEY': JSON.stringify(env.SOME_KEY)
    },
    plugins: [react()],
  }
Enter fullscreen mode Exit fullscreen mode

Complete code

Now, here's the before & after code.

The vite.config.ts file before:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
})
Enter fullscreen mode Exit fullscreen mode

the vite.config.ts file after:

import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '');
  return {
    define: {
      'process.env.SOME_KEY': JSON.stringify(env.SOME_KEY)
    },
    plugins: [react()],
  }
})
Enter fullscreen mode Exit fullscreen mode

Some final notes

So, if your like me, you'd be like: "but, wait a minute! Am I gonna have to manually write every single new key/value pair in the .env file, AND repeat myself in the vite.config.ts ?"

Well...this is exactly what this solution implies! I'm not happy about this, but at least it is a solution.

Why is is important to have this solution? Well because the CI/CD process on Netlify would fail because of the Uncaught ReferenceError: process is not defined error.

Alternative solution:

If you wish to avoid having to repeat the name of the keys in the vite.config.ts file, you could have the following:

import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '');
  return {
    define: {
      'process.env': env
    },
    plugins: [react()],
  }
})
Enter fullscreen mode Exit fullscreen mode

Disclaimer

You might not wish to expose the entire contents of process.env to the front end, so manually picking the keys/names of the values you wish to get access to in the front, becomes an sort of security device...

Also, notice that in the after code suggested where you do manually pick them, you might or might not have to stringify the selected keys' values.

A better alternative solution perhaps

I guess a solution somewhere in the middle would be to have an array containaing the name of the keys you wish to cherrypick from the process.env, and then loop over it, so as to dynamically generate the object that is assigned to the define key.

import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'

const cherryPickedKeys = [
  "SOME_KEY_IN_YOUR_ENV_FILE",
  "SOME_OTHER_KEY_IN_YOUR_ENV_FILE",
];

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '');
  const processEnv = {};
  cherryPickedKeys.forEach(key => processEnv[key] = env[key]);

  return {
    define: {
      'process.env': processEnv
    },
    plugins: [react()],
  }
})
Enter fullscreen mode Exit fullscreen mode

Final notes for TypeScript

If your project is in Typescript, an intellisense problem will pop up, which will also have the CI/CD process fail:

Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.ts(2580)
Enter fullscreen mode Exit fullscreen mode

And indeed, the solution to install the @types/node package, as suggested by VS Code, works and the problem goes away !

environment Article's
30 articles in total
Favicon
Understanding and Fixing the Externally-Managed-Environment Error
Favicon
Optimizing Environmental Resource Management with IoT and AI Integration
Favicon
The 3 Rules that 10x my Productivity (1 min read)
Favicon
Env-Core: An Easy Way to Validate Environment Variables in Node.js Projects
Favicon
Handling Environment Variables in Vite
Favicon
PDF Scan File Size: What To Do About It.
Favicon
Anaconda Installation and Virtual Environments: A Comprehensive Guide for Windows, Linux, and macOS
Favicon
A greener planet with tech
Favicon
Setting Up a Development Environment Using Laravel Sail (Docker)
Favicon
Daniel Siegel Alonso Suggests Sustainable Practices for the Music Industry
Favicon
@Environment variables
Favicon
Ongoing Carbon Emission Reduction Efforts Beneficial to Global Blue Ammonia Market Growth
Favicon
Parsing structured environment variables in Rust
Favicon
Sustainable Practices in Sports Turf Manufacturing: Reducing Environmental Footprint
Favicon
Adding Environment Variables to Your Webpack Project
Favicon
Building Environmental Analyzer using Lyzr SDK
Favicon
Playing with Python in node
Favicon
PHP on Manjaro with ASDF
Favicon
Harnessing Solar Power: The Key to Environmental Protection
Favicon
Navigating Challenges in Scaling Your Engineering Team: Strategies for Success
Favicon
Displaying air quality data in the terminal
Favicon
Dotenv: Python app environment variable vs. Linux environment variable
Favicon
Uncaught ReferenceError: process is not defined
Favicon
How to Get Environment Specific Configuration at Runtime in Angular
Favicon
How cryptocurrency destroys environment
Favicon
Python Virtual Environments
Favicon
shell 變數與環境變數
Favicon
The intersectionality of web performance
Favicon
Setting up an Alias for a Directory in Apache2 Server
Favicon
PyEnv & Poetry - BFFs 💖

Featured ones: