56

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
  • 18,575
  • 19
  • 87
  • 153
Kantharis
  • 826
  • 1
  • 7
  • 19
  • 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

8 Answers8

23

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,074
  • 5
  • 40
  • 61
  • 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
15

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
  • 820
  • 10
  • 14
  • 3
    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
  • 1
    dont know how but i need to bookmark this answer – ndotie Feb 13 '22 at 10:15
7

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
  • 339
  • 5
  • 7
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

  • 9
    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. – iRohitBhatia Jul 12 '19 at 04:08
  • 2
    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
  • 7,748
  • 5
  • 45
  • 78
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
  • 427
  • 5
  • 13
1

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
  • 5,065
  • 2
  • 29
  • 34
  • 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
1

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

Rhinolamer
  • 1,541
  • 1
  • 6
  • 8