Solve - Cannot find module 'cors' error in Node.js


Borislav Hadzhiev

Last updated: Mar 27, 2022


Photo from Unsplash

Solve - Cannot find module 'cors' error in Node.js #

To solve the error "Cannot find module 'cors'", make sure to install the cors package by opening your terminal in your project's root directory and running the following command: npm i cors. If you use TypeScript, install the typings by running npm i -D @types/cors.

cannot find module cors

Here is an example of how the error occurs.

// ⛔️ Error Cannot find module 'cors' // [ERR_MODULE_NOT_FOUND]: Cannot find package 'cors' // imported from bobbyhadz-js/index.js const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors()); app.get('/products/:id', function (req, res, next) { res.json({msg: 'This is CORS-enabled for all origins!'}); }); app.listen(1234, function () { console.log('CORS-enabled web server listening on port 1234'); });

Open your terminal in your project's root directory (where your package.json file is located) and run the following commands:

npm install cors # 👇️ only if you use TypeScript npm install --save-dev @types/cors

This will add the cors package to the dependencies of your project.

If the error is not resolved, try to delete your node_modules and package-lock.json (not package.json) files, re-run npm install and restart your IDE.

# 👇️ delete node_modules and package-lock.json rm -rf node_modules rm -f package-lock.json # 👇️ clean npm cache npm cache clean --force npm install
Make sure to restart your IDE and dev server if the error still persists. VSCode often glitches and a reboot solves things sometimes.

If you use TypeScript and get the error "Cannot find module 'cors' or its corresponding type declarations", run npm install --save-dev @types/cors and make sure the types array contains the string node.

{ "compilerOptions": { "types": [ "node" ] }, }
This should fix the error and now TypeScript should be able to find the type definitions for the cors module.

If you're still getting the "Cannot find module 'cors'" error, open your package.json file and make sure it contains the cors package in the dependencies object.

{ // ... rest "dependencies": { "cors": "^2.8.5", }, "devDependencies": { // 👇️ only if you use TypeScript "@types/cors": "^2.8.12", } }

You can try to manually add the line and re-run npm install.

npm install

Or install the latest version of the package:

npm install cors@latest npm install --save-dev @types/cors@latest
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.