99

I am using node.js to create a web application. When I run the application (either by opening index.html on the browser or using the command "npm start" on the terminal) I get two errors:

Uncaught ReferenceError: process is not defined

Uncaught ReferenceError: require is not defined

I solved the "require is not defined" error by specifically including in my index.html head tag the link to this script, where the require function is defined. However, I cannot find something similar for the process function.

My question is doublefold:

  1. Why do built-in node.js modules need to be re-defined? Why are they not recognized as they are, that is "built-in modules"? Doesn't the term "built-in module" mean that a module need not be redefined externaly/second-handedly?

  2. Is there a way to solve this problem? My script is very simple, I am just trying to use a basic function of node.js, so I cannot figure out what errors I might have done.

If anyone has come about this problem and has found a way around it or a reason this happens, you would be of great help.

Gabriel Petrovay
  • 20,476
  • 22
  • 97
  • 168
Kantharis
  • 1,316
  • 1
  • 11
  • 21
  • Hi everyone! Thank's for still trying to answer this question! This question is most probably moot at the moment (and potentially does not apply to present tools), since 6 years have passed, and in the meantime web app technologies have seen leaps of progress, and also the development process has been simplified a lot. It's interesting, though, to see that sometimes it's still valid. – Kantharis Feb 25 '21 at 12:45

17 Answers17

31

Webpack can inject environment variables into the "client side" .js code (very useful in case of SPA/PWA). You should define them as plugins in webpack.config.js

webpack.config.js

module.exports = {
plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
      'process.env.MY_ENV': JSON.stringify(process.env.MY_ENV),
      ... and so on ...
    })
],
}

Now you can access it on client side:

app.js

// Something like that
if(process.env.NODE_ENV === 'debug'){
    setDebugLevel(1)
}
Makc
  • 1,012
  • 12
  • 16
  • 5
    I don't know why, but I all of a sudden needed this when migrating a project's webpack from 3 to 5 (and CLI from 3 to 4). Thanks! – n8jadams Jun 14 '21 at 13:06
  • 2
    Great tip, it helped me with Firebase client-side credentials getting determined by the APP Environment we're running. – Jean Costa Sep 07 '21 at 17:14
  • 2
    dont know how but i need to bookmark this answer – ndotie Feb 13 '22 at 10:15
  • 1
    Yes. dotenv-webpack is a great way to do just that. https://www.npmjs.com/package/dotenv-webpack – ginna Dec 21 '22 at 00:06
28

Node.js code must be run by the node process, not the browser (the code must run in the server).

To run the code, you must run the command:

node server.js

And then you can access your server from a browser by typing "http://localhost:8080", for example. You must have a file server.js (or whatever) with the server code you want (in this case, creating a web server in port 8080).

You can follow this easy example, using express as http server module: http://expressjs.com/starter/hello-world.html

greuze
  • 4,250
  • 5
  • 43
  • 62
  • I am using the command "npm start" which refers to the "start" script inside package.json that is set to "start": "http-server -a localhost -p 8000 -c-1", so it basically does this, it runs to a local server I create. Still, I get "process is not defined". So it must be another problem. Thanks though. – Kantharis May 14 '15 at 17:02
  • In scripts/start property I usually have something like: "start": "node server.js", if you have directly a node.js script, the first line must be "#!/usr/bin/env node" or similar. However, try to run directly with node command. Posting the code, could clarify the problem. – greuze May 15 '15 at 11:59
9

If you are facing this problem and you are using webpack, you can get the desired process data injected into the client bundle by using DefinePlugin within your webpack.config.js.

In the example below, I show how to add several things to process.env object to make available within the browser:

  1. all the environment variables inside .env using the library dotenv
  2. the value of NODE_ENV, which is either 'development' or 'production'

Working example

# .env

API_KEY=taco-tues-123
API_SECRET=secret_tacos
// webpack.config.js

const dotenv = require('dotenv').config({ path: __dirname + '/.env' })
const isDevelopment = process.env.NODE_ENV !== 'production'

module.exports = {
  plugins: [
    new webpack.DefinePlugin({
      'process.env': JSON.stringify(dotenv.parsed),
      'process.env.NODE_ENV': JSON.stringify(isDevelopment ? 'development' : 'production'),
    }),
  ].filter(Boolean),
}
// Within client side bundle (React)
// src/App.jsx

console.log(process.env)          // {API_KEY: "taco-tues-123", API_SECRET: "secret_tacos"}
console.log(process.env.NODE_ENV) // development

Notice that console.log(process.env) only has the values from the .env file, and that NODE_ENV is not a part of the process.env object.

In the example below, I show how I was trying to inject the process.env object which led me to this stack overflow. I also include a highlight from the webpack documentation on why the code below was not working.

Broken example

module.exports = {
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        ...dotenv.parsed,
        'NODE_ENV': JSON.stringify(isDevelopment ? 'development' : 'production')
      }
    }),
  ].filter(Boolean),
}
// Within client side bundle (React)
// src/App.jsx

console.log(process.env)          // Uncaught ReferenceError: taco is not defined
console.log(process.env.NODE_ENV) // development

From the webpack DefinePlugin docs:

Warning When defining values for process prefer

'process.env.NODE_ENV': JSON.stringify('production')

over

process: { env: { NODE_ENV: JSON.stringify('production') } }

Using the latter will overwrite the process object which can break compatibility with some modules that expect other values on the process object to be defined.

!Warning!

Injecting dotenv.parsed into the client bundle as described will expose these secrets to the client. For development purposes, not a big deal, but in a deployed production environment, any passwords or private api keys will be visible to anyone that goes looking for them.

taco_friday
  • 469
  • 7
  • 7
7

Below solution for Uncaught ReferenceError: process is not defined:

  1. if you are using CRA (create react app), use process.env.
  2. if you are using ViteJS, use import.meta.env.

Read more here about how to import env process in Vite: https://vitejs.dev/guide/env-and-mode.html

Examples:

CRA: process.env.API_BASE_URL

Vite: import.meta.env.VITE_API_BASE_URL

jhon26
  • 313
  • 2
  • 11
6

You can add the following to your package.json file

{
"name": "mypackage",//default
"version": "0.0.1", //default
"eslintConfig": {
    "env": {
        "browser": true,
        "node": true
    }
}}

More Explanation

Lameck Meshack
  • 4,707
  • 2
  • 10
  • 17
5

I had this issue, and for some reason no amount of fiddling around with the webpack.config.js using the other suggestions would resolve it. I suspect some packages I'm using are written incorrectly for the browser, or there might be something wrong with my environment.

I ended up "fixing" it by adding the following code to my HTML file above all other <script> file references. .

    <script>
        // Required by some npm packages
        window.process = { browser: true, env: { ENVIRONMENT: 'BROWSER' } };
    </script>
George
  • 131
  • 1
  • 5
  • 1
    This solution also solved this error for me. If you are using React, open your index.html file inside the public folder, copy paste the code above into your index.html file, restart your IDE and restart your server. – Martin Oputa Jun 09 '23 at 09:22
4

I had the same problem solved it by going into my .eslintrc.js file to configure my globals variables, adding require and process to the globals variable and setting the corresponding value equal to "writable". Hope it works for you.

this link really helped https://eslint.org/docs/user-guide/configuring#specifying-globals

  • 10
    Hey Oluwatobi! Welcome to SOF, for future answers, My personal suggestion would be to add some code or explain things be pasting the snippets of code. – Alwaysblue Jul 12 '19 at 04:08
  • 3
    Hey @Oluwatobi. Your approach seams interesting. Can you add your working `.eslintrc` file? – zeamedia Feb 19 '21 at 19:01
4

I was just getting this error (Uncaught ReferenceError: process is not defined) in a local hot-reloading Quasar (Vue) app when calling a particular endpoint. The fix for me ended up being to just restart the hot-reloading server (I hadn't reloaded it since adding the process.env.MY_VARIABLE code).

Nathan Wailes
  • 9,872
  • 7
  • 57
  • 95
3

I had same problem when I tried to do this node js app: https://www.youtube.com/watch?v=mr9Mtm_TRpw

The require in html was reached from a < script> and was undefined, like

<script> require('./renderer.js');</script>

I changed it to:

<script src="./renderer.js"></script>

The process in html script was also undefined. I included the webPreferences: nodeIntegration in the js file:

win = new BrowserWindow({
    width: 800, 
    height:600, 
    icon: __dirname+'/img/sysinfo.png', 
    webPreferences: {
        nodeIntegration: true
    }
});

I hope it helped.

Zeghra
  • 447
  • 5
  • 14
2

If you are using the npm module dotenv-webpack with Webpack 3, it might be because you are using destructuring, like so:

const { ENV1, ENV2 } = process.env;

This is a known issue.

Ugly workaround is:

const { ENV1 } = process.env;
const { ENV2 } = process.env;
jfunk
  • 7,176
  • 4
  • 37
  • 38
  • I was seeing the error in a NextJs project using destructuring and your 'ugly' workaround fixed the issue, but I was also able to continue using destructuring if I include `const process = require("process")` before calling `const { ENV1, ENV2 } = process.env`. – w. Patrick Gale Nov 12 '21 at 01:49
2

Add ProvidePlugin to the plugins section in webpack 5+ config:

plugins: [
  ...,
  new webpack.ProvidePlugin({
    process: 'process/browser',
    Buffer: ['buffer', 'Buffer']
  }),
  ...
]
Per Quested Aronsson
  • 11,380
  • 8
  • 54
  • 76
1

If you followed all answers here but still have same error then try this. The error is caused by the react-error-overlay package which has dependencies that were updated to support webpack v5 and are not compatible with react-scripts v4. So to solve the Uncaught ReferenceError: process is not defined in React, open your terminal in your project's root directory and update the version of your react-scripts package by running npm install react-scripts@latest and re-install your dependencies if necessary. You can find more detailed answers in here

Alchemist
  • 325
  • 1
  • 17
0

I commit and push my code to the repo, then delete all old code, clone it again. run npm i to install all dependencies. Then it worked. Amazing!!!!

0

Running npm install fixed the issue for me.

  • Hi, can you add more details? This is a generic answer.... How can `npm install` solve the problem? Please read [how to answer](https://stackoverflow.com/help/how-to-answer) – pierpy May 10 '23 at 10:57
0

I had the same error. To fix it install the package with

npm install process

I had this error in a react project so I imported the package into the file where the error was occurring.

import process from 'process'
demonkoryu
  • 1,247
  • 10
  • 27
0

If you use vite try

import.meta.env.MONGO_URI instead of

process.env

In my case this solved the problem.

0

Actually I had facing this error with Nuxt3, in my deployed Vercel app. Because library implemented @web3auth/... has some polyfill issues to solve.

First I needed to install packages pnpm add --save-dev buffer process, Then I call them in my layout by default.

<script type="module" lang="ts">
// Global node polyfill.
import { Buffer } from "buffer";
import process from "process";
window.global = window;
window.Buffer = Buffer;
window.process = process;
</script>
Maik col
  • 31
  • 4