Search code examples
javascriptnode.jsknex.jsdotenv

knexfile.js does not read Dotenv variables


So I am trying out knexjs and the first setup works like a charm. I've set up my connection, created a datastructure and in my terminal i ran $ knex migrate:latest. It all worked fine... the migrated tables showed up in my database ran the migrate again and got Already up to date.

Now here is where I get an issue: Using Dotenv... Here is my code:

require('dotenv').config();

module.exports = {

        development: {

            client: process.env.DB_CLIENT,
            connection: {

                host: process.env.DB_HOST,

                user: process.env.DB_ROOT,
                password: process.env.DB_PASS,

                database: process.env.DB_NAME,
                charset: process.env.DB_CHARSET

            }
        }
};

As far as i can see nothing wrong with it and when i run the script through node no errors show up. Then I wanted to check if I still could do a migrate and i get the following error:

Error: ER_ACCESS_DENIED_ERROR: Access denied for user ''@'[MY IP]' (using password: YES)

I am using the same vars only this time from my .env file. But when i look at the error nothing is loaded from it, and yes both the knexfile.js and .env are in the root of my project :) Among the things i tried is setting the path in different ways within require('dotenv').config(); but then it would throw an error from dotenv meaning the file was already correctly loaded.

Can anyone help me figuring this out?


Solution

  • So after some trial and error i finally figured out what was wrong. I don't know what caused it but somehow the install of Knex wasn't done properly...

    I un- and reinstalled Knex (local and global). Then first I installed it on the global level and than as a dependency. After that I initialized Knex again ( $ knex init ) and started from the ground up.

    I think, but i am still not sure why because i could not find any info about it, the order of installing Knex matters (or mattered in my case and i am not even sure what i did wrong the first time).

    On the side

    If you are new to Knex and just blindly follow a random tutorial/article and just create a new file for Knex (i.e. knexfile.js), Knex will still work but other packages could fail to execute properly. This is what i don't see in most articles i found, read the documentation on how to generate the files needed (migrations and seeds). Most articles don't cover these steps properly.

    Hope this is worth anything