Search code examples
mysqlnode.jsnpm

Nodejs - unable to load environment variable in mysql2


I am using the mysql2 package for connecting node with MySQL and I am using a .env file to store my username and password. But when I use it in my config for connecting MySql it doesn't load. It throws the following error whenever I hit an endpoint using Postman.

Error: Access denied for user 'undefined'@'localhost' (using password: YES)

Below is my code:

const express = require("express");
const router = express.Router();
const mysql = require("mysql2");

const connection = mysql.createPool({
    user: `${process.env.DB_USERNAME}`,
    host: "localhost",
    password: `${process.env.DB_PASSWORD}`,
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0,
    database: "issue",
});

I am using dotenv to load env variables and initialized in my entry file as:

require('dotenv').config();

What am I doing wrong?


Solution

  • As a side effect of the way JavaScript coerces types, process.env.foo will result in "undefined" if it is undefined and used in a string.

    There is either a typo in your dotenv config file or else some other problem with your use of dotenv.

    I would recommend more defensive coding to give a better error message when this happens. (The following code is untested, but you will no doubt get the idea.)

    const express = require("express");
    const router = express.Router();
    const mysql = require("mysql2");
    
    const dbUsername = process.env.DB_USERNAME;
    const dbPassword = process.env.DB_PASSWORD;
    
    if (!dbUsername) {
        throw new Error('DB_USERNAME environment variables must be set');
    }
    
    if (!dbPassword) {
                throw new Error('DB_PASSWORD environment variables must be set');
    }
    
    const connection = mysql.createPool({
        user: dbUsername,
        host: "localhost",
        password: dbPassword,
        waitForConnections: true,
        connectionLimit: 10,
        queueLimit: 0,
        database: "issue",
    });