Andrii Radkevych
Andrii Radkevych

Reputation: 3432

Correct way to use dotenv-expand (.env)

https://github.com/motdotla/dotenv-expand

POSTGRES_DB=postgresdb
POSTGRES_PASSWORD=password
POSTGRES_USER=postgresadmin
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
PORT=3000
DATABASE_URL=postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}

Is it correct way to use dotenv-expand? If so , it doens't work in my case . I want to create variable related to variables above:

DATABASE_URL=postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}

but when I check it by using process.env.DATABASE_URL - it returns me the same varialbe like you see above without changing ${POSTGRES_USER} on the corresponding parameter

import dotenv from 'dotenv';
import dotenvExpand from 'dotenv-expand';

const config = dotenv.config();

dotenvExpand(config);

And here you can see how I initialize dotenv-expand with dotenv

Upvotes: 6

Views: 12535

Answers (2)

Tory
Tory

Reputation: 91

import dotenv from 'dotenv';
import dotenvExpand from 'dotenv-expand';

const config = dotenv.config();

Try to replace

dotenvExpand(config);

with

dotenvExpand.expand(config);

Upvotes: 6

pzaenger
pzaenger

Reputation: 11984

Using your code, like:

import dotenv from 'dotenv';
import dotenvExpand from 'dotenv-expand';

const config = dotenv.config();

dotenvExpand(config);

console.log(config);

I get the following error:

(node:23421) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

Changing your code to:

const dotenv = require('dotenv');
const dotenvExpand = require('dotenv-expand');

const config = dotenv.config();

dotenvExpand(config);

console.log(config);

I get the desired output:

{
  parsed: {
    POSTGRES_DB: 'postgresdb',
    POSTGRES_PASSWORD: 'password',
    POSTGRES_USER: 'postgresadmin',
    POSTGRES_HOST: 'localhost',
    POSTGRES_PORT: '5432',
    PORT: '3000',
    DATABASE_URL: 'postgres://postgresadmin:password@localhost:5432/postgresdb'
  }
}

If you want to stick to import, add "type": "module" to your package.json.

Edit:

console.log(process.env.DATABASE_URL); works fine.

My whole setup:

mkdir dotenv-test && cd dotenv-test
npm init -y
npm install dotenv dotenv-expand
touch .env
rouch .index.js
(copying .env and code)
node index.js

Upvotes: 3

Related Questions