Launch Offer: Use codelaunch30for 30% off

password authentication failed

This error occurs when the password provided for a PostgreSQL user is incorrect or the user doesn't exist.

The password authentication failed error means the credentials are wrong.

Understanding the Error

FATAL: password authentication failed for user "myuser"

The username or password doesn't match what's configured in PostgreSQL.

Common Causes

1. Wrong Password

Simply typing the wrong password for the user.

2. Wrong Username

# Trying to connect as wrong user
psql -U wronguser -d mydb

3. User Doesn't Exist

SQL
-- User was never created
CREATE USER myuser WITH PASSWORD 'secret';

4. Password Changed

Password was changed but application has old password.

5. Environment Variable Issues

BASH
# PGPASSWORD not set or has wrong value
export PGPASSWORD='correct_password'

How to Fix It

Solution 1: Reset the Password

SQL
-- Connect as superuser (postgres)
psql -U postgres

-- Reset password
ALTER USER myuser WITH PASSWORD 'newpassword';

Solution 2: Create the User

SQL
-- Create user if it doesn't exist
CREATE USER myuser WITH PASSWORD 'secret';

-- Grant necessary permissions
GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;

Solution 3: Check pg_hba.conf

BASH
# Find config file location
psql -U postgres -c "SHOW hba_file;"

# Edit authentication settings
sudo nano /etc/postgresql/15/main/pg_hba.conf

Common pg_hba.conf entries:

# TYPE  DATABASE    USER        ADDRESS         METHOD
local   all         all                         peer
host    all         all         127.0.0.1/32    md5
host    all         all         ::1/128         md5

Solution 4: Use .pgpass File

BASH
# Create .pgpass file for password-less connections
echo "localhost:5432:mydb:myuser:secret" >> ~/.pgpass
chmod 600 ~/.pgpass

Solution 5: Check Connection String

JAVASCRIPT
// Verify connection string
const connectionString = 'postgresql://myuser:secret@localhost:5432/mydb';

// Or as object
const config = {
  user: 'myuser',
  password: 'secret',
  host: 'localhost',
  port: 5432,
  database: 'mydb'
};

Solution 6: Use Environment Variables

BASH
export PGUSER=myuser
export PGPASSWORD=secret
export PGHOST=localhost
export PGDATABASE=mydb

psql  # Will use these variables

Checking User Exists

SQL
-- List all users
SELECT usename FROM pg_user;

-- Or
\du

Best Practices

  1. Use strong passwords with mix of characters
  2. Store passwords securely in environment variables or secrets manager
  3. Rotate passwords periodically
  4. Use connection pooling to avoid exposing credentials
  5. Limit user permissions to what's actually needed