Solve Error Uncaught ReferenceError: require is not defined in Node.js

While working with Node JS, you might be familiar with the require() and sometimes, it shows error like Uncaught ReferenceError: require is not defined.

So why does this happens? Let’s see in today’s post.

Before coming to the error, let’s know what is require() used for.

What is require?

The require function is the builtin function of node js that helps us to include local or node_modules in our project that exists in a separate file.

Here, we have imported express module into our code using require('express'). The require function will look for files in builtin core modules, NPM modules(node_modules), local modules, etc.

require is not defined

Now, let’s see what is the reason for the error. Here is an example code.

Serve this code using node’s http-server and it will show server running in the console but when you will fire it in the browser, you’ll get Uncaught ReferenceError: require is not defined.

Now, why does this happened?

The require function is defined only in node js and it has nothing to do with the browser. Both Node JS and chrome has Javascript’s V8 engine but both of them are completely different in terms of running js. Your browser is capable of running only client-side javascript. To run this code without any kind of error, you need to install node on your system. Here is a detailed guide on installing node js on Mac, Windows or Linux.

Once installed, fire a terminal and type node -v to check if it is successfully installed or not.

To run this code without error, save this file as app.js and run it in your terminal using the command node app.js The code will show the output in the terminal server running. This means your code is running without any problem.

Well, this was all about the function require() and the error related to it. If you stuck into any kind of error, don’t forget to google it and try to debug it on your own. This will teach you how to debug on your own as someone might have faced a similar problem earlier.

If you still don’t find any solution for your problem, you can ask your doubt in the comment’s section below and we’ll get back to you🤓.

Leave a Reply

Your email address will not be published. Required fields are marked *