Installation

  1. First install the knex library with this command.
npm install knex
  1. Second install the database library with database we are using in my case i am using PostgreSQL.
npm install pg

Configration

  1. Now run the npx knex init this will create the knex config file. Knexfile mainly contain the config for different-different environment like development, staging, and production.

Here is the code for knexfile.js config.

module.exports = {
  development: {
    client: "pg",
    connection: {
      host: "127.0.0.1",
      user: "db_user",
      password: "db_password",
      database: "db_name",
      port: 5432,
    },
    migrations: {
      directory: "./migrations",
      tableName: "knex_migrations",
    },
  },

  staging: {
    client: "pg",
    connection: {
      database: "my_db",
      user: "username",
      password: "password",
    },
    pool: {
      min: 2,
      max: 10,
    },
    migrations: {
      tableName: "knex_migrations",
    },
  },

  production: {
    client: "pg",
    connection: {
      connectionString: process.env.DATABASE_URL,
      ssl: { rejectUnauthorized: false },
    },
    pool: {
      min: 2,
      max: 10,
    },
    migrations: {
      directory: "./migrations",
      tableName: "knex_migrations",
    },
  },
};

client

Specifies the database type knex will use. For PostgreSQL use ‘pg’ library.

client: "pg"

connection

This is how knex connects to your database. It can be an object or connection string.

connection: {
	host: '127.0.0.1',
	user: 'username',
	password: 'password',
	database: 'dbname',
	port: 5432,
}

OR

connection: {
	connectionString: "process.env.DATABSE_URL"
	ssl: { rejectUnauthorized: false },
}

Pool

A connection pool is set of reusable database connection that Knex keeps open.

Instead of opening new connection every time your app queries the database, Knex takes one from the pool - use it - then return back to the pool.