Uncaught ReferenceError: process is not defined

143,526

Solution 1

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

Solution 2

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)
}

Solution 3

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.

Solution 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

Solution 5

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).

Share:
143,526
Kantharis
Author by

Kantharis

Senior Software Engineer at Nrwl. Working on Nx. Internet indigenous. I love web.

Updated on February 07, 2022

Comments

  • Kantharis
    Kantharis over 2 years

    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.

  • Kantharis
    Kantharis almost 9 years
    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.
  • greuze
    greuze almost 9 years
    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.
  • iRohitBhatia
    iRohitBhatia almost 5 years
    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.
  • paddotk
    paddotk almost 4 years
    That's for Electron, while the question states it's a web app.
  • zeamedia
    zeamedia about 3 years
    Hey @Oluwatobi. Your approach seams interesting. Can you add your working .eslintrc file?
  • n8jadams
    n8jadams almost 3 years
    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!
  • Jean Costa
    Jean Costa over 2 years
    Great tip, it helped me with Firebase client-side credentials getting determined by the APP Environment we're running.
  • w. Patrick Gale
    w. Patrick Gale over 2 years
    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.
  • ndotie
    ndotie about 2 years
    dont know how but i need to bookmark this answer