9

I have node.js application I have installed dotenv and add the following configuration in my .env file

 DB_HOST='localhost'
 DB_Database=TheDatabasename
 DB_USER=TheUser
 DB_PASS=thePassword
 DB_PORT=1433

I am using sqlserver I call dotenv like bellow:

const sql = require('mssql');
const dotenv = require('dotenv');
dotenv.config();

const config = {
 user: process.env.DB_USER,
 password: process.env.DB_PASS,
 server: process.env.DB_HOST, 
 database: process.env.DB_Database,
 port: process.env.DB_PORT,
}

 const poolPromise = new sql.ConnectionPool(config)
.connect()
.then(pool => {
 console.log('Connected to MSSQL')
 return pool
})
 .catch(err => console.log('Database Connection Failed! Bad Config: ', err))

 module.exports = {
  sql, poolPromise
 }

I get the following error:

  Database Connection Failed! Bad Config:  TypeError: The "config.options.port" property must be of type number.
MJ X
  • 8,506
  • 12
  • 74
  • 99
  • 5
    Try `port : parseInt(process.env.DB_PORT);` – rodrigoap Nov 04 '19 at 19:24
  • 2
    When you read from your .env file, the values are returned as string. You need to parse them to appropriate types (in this case, integer) - parseInt(process.env.DB_PORT) – Rvy Pandey Nov 04 '19 at 19:27

2 Answers2

16

Mssql, require a type number in the port parameter and the environment variables are string.

You should cast the value before sent to the driver

...
 port: parseInt(process.env.DB_PORT, 10),
...
Yeinso Blanco
  • 193
  • 1
  • 6
  • How to do this in typescript? When I try to run the code it throws "Argument of type 'string | undefined' is not assignable to parameter of type 'string'" – cwallenwein Jun 11 '21 at 21:42
  • 2
    I think you should use a fallback... `parseInt(process.env.DB_PORT || "", 10) ` – Yeinso Blanco Jul 02 '21 at 19:02
-1

All Environment Variables are STRINGS, So just convert the port to INT.

const config = {
  user: process.env.DB_USER,
  password: process.env.DB_PASS,
  server: process.env.DB_HOST,
  database: process.env.DB_DATABASE,
  port: +process.env.DB_PORT,
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000,
  },
  options: {
    encrypt: false,
    trustedServerCertificate: false,
  },
};