Last modified: Jun 30, 2025 By Alexander Williams

Fix Error: Cannot find module 'pg'

If you see the error Error: Cannot find module 'pg', don't worry. This is a common issue in Node.js when the PostgreSQL client library is missing. Let's fix it.

What Causes the Error?

The error occurs when Node.js cannot locate the pg module. This happens if the module isn't installed or there's a path issue.

Common causes include:

  • The pg package isn't installed.
  • Installation was done in the wrong directory.
  • Node.js cannot access the module due to permissions.

How to Fix the Error

Follow these steps to resolve the issue.

1. Install the 'pg' Module

First, ensure the pg module is installed. Run this command in your project directory:


npm install pg

If you need it globally (not recommended), use:


npm install -g pg

2. Check package.json

Verify that pg is listed in your package.json under dependencies. If not, reinstall it.


{
  "dependencies": {
    "pg": "^8.8.0"
  }
}

3. Verify Node Modules

Ensure the node_modules folder exists in your project. If missing, run:


npm install

4. Rebuild Dependencies

Sometimes, dependencies need rebuilding. Use:


npm rebuild

5. Check File Permissions

Ensure you have read/write permissions for the node_modules folder. Fix permissions if needed.

Example Code

Here’s a simple example using the pg module:


const { Client } = require('pg');

const client = new Client({
  user: 'postgres',
  host: 'localhost',
  database: 'mydb',
  password: 'password',
  port: 5432,
});

client.connect()
  .then(() => console.log('Connected to PostgreSQL'))
  .catch(err => console.error('Connection error', err));

If the module is missing, you'll see the error. Install it first.

Common Mistakes

Avoid these mistakes:

  • Installing pg in the wrong directory.
  • Forgetting to run npm install after cloning a project.
  • Using an outdated Node.js or npm version.

Troubleshooting

If the error persists, try:

  • Updating Node.js and npm.
  • Deleting node_modules and reinstalling.
  • Checking for typos in require('pg').

For similar errors like Fix Error: Cannot find module 'mysql2' or Fix Error: Cannot find module 'socket.io', the solutions are similar.

Conclusion

The Cannot find module 'pg' error is easy to fix. Install the module, check dependencies, and verify paths. If you face other module errors, like Fix Error: Cannot find module 'typescript', apply similar steps.

Now you can connect to PostgreSQL without issues. Happy coding!