Last modified: Jun 30, 2025 By Alexander Williams
Fix Error: Cannot find module 'mysql2'
If you see the error Cannot find module 'mysql2', don't worry. This is a common issue in Node.js. It means your project can't locate the mysql2 package.
Why does this error occur?
The error happens when Node.js can't find the mysql2 module in your project. This usually occurs because:
1. The package isn't installed
2. It's installed in the wrong directory
3. There's a version conflict
How to fix the mysql2 module error
1. Install mysql2 package
The simplest fix is to install the package. Run this command in your project directory:
npm install mysql2
This will download mysql2 and add it to your node_modules
folder.
2. Check package.json
Ensure mysql2 is listed in your package.json
. If not, install it with --save
:
npm install mysql2 --save
3. Verify installation location
Sometimes packages install globally. Check where mysql2 is installed:
npm list mysql2
If it's not in your project's node_modules
, install it locally.
4. Rebuild node modules
If the error persists, try deleting node_modules
and reinstalling:
rm -rf node_modules
npm install
5. Check Node.js version
Some mysql2 versions need specific Node.js versions. Check compatibility in the mysql2 docs.
Common mistakes to avoid
1. Installing globally when you need local installation
2. Forgetting to run npm install
after cloning a project
3. Having multiple Node.js versions installed
Example code with mysql2
Here's how to properly use mysql2 in your project:
// Import mysql2
const mysql = require('mysql2');
// Create connection
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'test'
});
// Execute query
connection.query(
'SELECT * FROM users',
function(err, results) {
console.log(results);
}
);
Troubleshooting other module errors
If you face similar errors with other modules, check our guides:
Fix Error: Cannot find module 'socket.io'
Fix Error: Cannot find module 'typescript'
Fix Error: Cannot find module 'webpack'
Conclusion
The Cannot find module 'mysql2' error is easy to fix. Just install the package correctly. Always check your package.json
and installation location.
Remember to use the right Node.js version. Keep your dependencies updated. This will prevent similar errors with other modules.