Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knex is not reading connection string from knexfile

I have been given a knexfile like this:

require('dotenv').config()

module.exports = {
  client: 'pg',
  connection: process.env.DB_CONNECTION,
  pool: {
    min: 2,
    max: 10
  },
  migrations: {
    tableName: 'knex_migrations'
  }
};

The connection string I supply is:

Host=localhost;Database=heypay;Username=postgres;Password=1234

However, Knex keeps issuing the error:

 password authentication failed for user "user"

Apparently, the username I have given is not user. Moreover, I have tried to hardcore the connection string into the connection filed under module.exports. This still ended up in vain.

like image 588
Alexander Ho Avatar asked Dec 03 '25 18:12

Alexander Ho


1 Answers

The trick is, the connection property can either be a string or an object. That's why you were able to supply an environment variable (it's a string).

The reason your original string was failing is not a Knex problem: Postgres connection strings have a slightly different format. You can use a similar approach as your first attempt, but pay attention to the key names:

host=localhost port=5432 dbname=mydb connect_timeout=10

Also note spaces, not semicolons. However in my experience most people use a Postgres URI:

postgresql://[user[:password]@][netloc][:port][,...][/dbname][?param1=value1&...]

So in your example, you'd use:

module.exports = {
  client: 'pg',
  connection: 'postgresql://your_database_user:password@localhost/myapp_test',
  pool: {
    min: 2,
    max: 10
  },
  migrations: {
    tableName: 'knex_migrations'
  }
};
like image 50
Rich Churcher Avatar answered Dec 06 '25 09:12

Rich Churcher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!