141

Just started working with Node.js. In my app/js file, I am doing something like this:

app.js

var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Am I really running a server?!');
}).listen(8080, '127.0.0.1');

console.log('running server!');

When I'm in my terminal and run node app.js, the console spits out 'running server!', but in my browser I get, Uncaught ReferenceError: require is not defined.

Can someone explain to me why in the terminal, it works correctly but in the browser, it doesn't?

I am using the node's http-server to serve my page.

4
  • 15
    Are you... running that js file in the browser? You're not meant to do that... Commented Aug 11, 2015 at 1:11
  • 3
    I had the same problem too, I just removed the "type": "module" line from the package.json file Commented Sep 12, 2021 at 9:02
  • @Synchro Thanks! I removed my package.json file and it worked. I'm just learning so it's not prod setup. Commented Oct 26, 2021 at 13:20
  • 1
    Because this is the top Google result: I was able to fix this error during an Angular 8->14 upgrade by removing "strict": true from my compilerOptions in tsconfig.json Commented Jun 21, 2023 at 23:48

9 Answers 9

163

This can now also happen in Node.js as of version 14.

It happens when you declare your package type as module in your package.json. If you do this, certain CommonJS variables can't be used, including require.

To fix this, remove "type": "module" from your package.json and make sure you don't have any files ending with .mjs.

Sign up to request clarification or add additional context in comments.

6 Comments

This can happen with anything in your project folder. So if you have an unrelated build script written with CommonJS imports but a project.json with "type": "module", then the build script will break, even if it's not referenced in the package.json.
You can still use require in a module using createRequire
You can also rename the file extension to .cjs
Using Node 14, taking out "type": "module" from package.json results (node:7396) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs. I don't have any .mjs
That way you can't use import.
|
129

As Abel said, ES Modules in Node >= 14 no longer have require by default.

If you want to add it, put this code at the top of your file:

import { createRequire } from 'module';
const require = createRequire(import.meta.url);

Source: https://nodejs.org/api/modules.html#modules_module_createrequire_filename

2 Comments

How can we add this in TypeScript so it adds this in our compiled JS after?
Life-saving solution. Would like to mention that npm initially caught some vulnerabilities which I fixed using audit --force. I am suspecting that those audited modules somehow triggered this issue as cited by @JoshuaWade's comment under this answer.
119

In the terminal, you are running the node application and it is running your script. That is a very different execution environment than directly running your script in the browser. While the Javascript language is largely the same (both V8 if you're running the Chrome browser), the rest of the execution environment such as libraries available are not the same.

node.js is a server-side Javascript execution environment that combines the V8 Javascript engine with a bunch of server-side libraries. require() is one such feature that node.js adds to the environment. So, when you run node in the terminal, you are running an environment that contains require().

require() is not a feature that is built into the browser. That is a specific feature of node.js, not of a browser. So, when you try to have the browser run your script, it does not have require().

There are ways to run some forms of node.js code in a browser (but not all). For example, you can get browser substitutes for require() that work similarly (though not identically).

But, you won't be running a web server in your browser as that is not something the browser has the capability to do.


You may be interested in browserify which lets you use node-style modules in a browser using require() statements.

2 Comments

@N73k - I won't take that as a serious question. If you want to read about node.js, what it is and what people use it for, that's a completely different topic and you can start by doing your own searches on the web and find all sorts of articles. Javascript is a real OOP language. Perhaps different than what you think you want, but that's only your opinion and there are many who do not share your opinion for a variety of reasons. This is not the place to debate or discuss that.
@HasinduDahanayake - What is the point of that inflammatory statement? JS is a very real object oriented language. Everything in the language is an object with methods, with classes, with an ability to extend classes or objects. It is loosely typed, but that doesn't make it any less OO.
66

Node.JS is a server-side technology, not a browser technology. Thus, Node-specific calls, like require(), do not work in the browser.

See browserify or webpack if you wish to serve browser-specific modules from Node.

2 Comments

i have the same problem and installed both browserify and webpack but the problem persists !!
Without knowing your particular configuration, I cannot help. Best to create a new question with your specific problem.
7

Just remove "type":"module" from your package.json.

3 Comments

Using Node 14, taking out "type": "module" from package.json results (node:7396) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs. I don't have any .mjs
it doesn't help.
this is not helping, you have to write a warning says "in case you don't have ES6 imports in your app files"
5

I solve this by doing this steps:-

step 1: create addRequire.js file at the project root.

step 2: inside addRequire.js add this lines of code

import { createRequire } from "module";
const require = createRequire(import.meta.url);

global.require = require; //this will make require at the global scobe and treat it like the original require

step 3: I imported the file at the app.js file head

import "./start/addRequire.js";

now you have require beside import across the whole project and you can use both anywhere.

Comments

1

Point 1: Add require() function calling line of code only in the app.js file or main.js file.

Point 2: Make sure the required package is installed by checking the pacakage.json file. If not updated, run "npm i".

Comments

1

My mistake: I installed ESLint to my project and made a mistake when I filled out the questionnaire and chose wrong type of modules) Maybe it will be helpful for someone))

What type of modules does your project use? · * commonjs

Comments

-1

I solve it, by removing below line from package.json file

 "type": "module"

Hope it will solve the problem.

1 Comment

This appears to be just a repeat of this existing answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.