require is not defined? Node.js

Richard Bustos picture Richard Bustos · Aug 11, 2015 · Viewed 427.3k times · Source

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.

Answer

Abel picture Abel · Feb 14, 2020

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.