I am attempting to use the value for NODE_ENV in my node.js server to connect to a different database when running my tests. How can I get the correct values for NODE_ENV i.e 'development', 'test', 'production' to make what I've got below work?
import pg from "pg";
import dotenv from "dotenv";
dotenv.config();
const Pool = pg.Pool;
const enviroment = () => {
if (process.env.NODE_ENV === "test") {
return process.env.TEST_DATABASE;
} else {
return process.env.DEVELOPMENT_DATABASE;
}
};
const pool = new Pool({
password: process.env.PASSWORD,
host: process.env.HOST,
port: process.env.PORT,
database: enviroment()
});
export default pool;
.env includes
NODE_ENV=development
NODE_ENV=production
NODE_ENV=test
Thanks.
Seems your code is fine. I think you made a typo in your .env file.
Here is a sample for your .env:
NODE_ENV=test
TEST_DATABASE=mongodb://localhost:27017
DEVELOPMENT_DATABASE=mongodb://localhost:27018
PASSWORD=abcxyz
HOST=localhost
PORT=8000
Don't use NODE_ENV="test", spaces, or anything like this.
Related
const app=require('./app')
const dotenv =require('dotenv');
const PORT=3000;
dotenv.config({path:'backend/config/config.env'})
app.listen(process.env.PORT,()=>{
console.log(`server Started on Port: ${process.env.PORT} in ${process.env.NODE_ENV}mode`);
})
const app=require('./app')
const dotenv =require('dotenv');
const PORT=3000;
dotenv.config({path:'backend/config/config.env'})
app.listen(process.env.PORT,()=>{
console.log(`server Started on Port: ${process.env.PORT} in ${process.env.NODE_ENV}mode`);
})
I am getting error as follows:
server Started on Port: undefined in undefined mode
You need to make a file on the root say local.env of your project and assign variable values in that.
PORT=3000
NODE_ENV=DEVELOPMENT
I am trying to implement an auth service using node-express-postgres.
I had the pool configed as such:
const Pool = require('pg').Pool;
const pool = new Pool({
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
port: 5432
});
module.exports = pool;
I am trying to do the following call as a simple test for connection:
const express = require('express');
const router = express.Router();
const pool = require('../db');
const bcrypt = require('bcryptjs');
router.post('/login', async (req, res) => {
try {
let temp = await pool.query("SELECT * FROM records");
console.log(temp)
} catch (error) {
console.log(error.message);
}
});
When I send a post request to this endpoint my app crash with the following error:
Error: SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string
I have checked all my env vars and they are correct.
Any idea why it is failing to do any operation on the postgres DB?
It seems, that node didn't read .env file.
You can check it with
console.log(process.env.DB_PASSWORD);
It can be fixed with package 'dotenv', for example.
npm i --save dotenv
And then in first line in index.js
require('dotenv').config();
For me configuring 'dotenv' resolved error
require('dotenv').config();
Check your postgres password if it's correct. I had a similar problem while working on a mac, by default the
posgreSQL user is "posgres" and password is "root"
In my case I had something like
...
USER: "postgres",
PASSWORD: "",
...
which generated the error
you probably should indicate your .env file location inside of the config
require('dotenv').config({ path: '../.env' });
dotenv configurations
Fixed it by updating npm script.
cross-env NODE_ENV=development nest start
Installed "cross-env" to set NODE_ENV.
If our code is not able to find .development.env file or unable to find password, then this error will be thrown.
Check out the path in your IDE folder, when i checked, it was by one path below, so i moved it in the correct folder and boom, it all worked.
I have this given module in config.js. I want to include this is my index.js. I tried multiple ways but config variable is always undefined.
I tried like this.
const config = require('./config') //undefined
const config = require('./config')("dev") //error
const config = require('./config')["dev"] // error
const config = require('./config').get("dev")
Here is how i run it
// my command.
npm run start:dev
"scripts": {
"start:prod": "set NODE_ENV=prod pm2 start index.js --watch",
"start:dev": "set NODE_ENV=dev && node index.js"
},
Here is module
let env = process.env.NODE_ENV;
require('dotenv').config();
const dev = {
app: {
port: parseInt(process.env.DEV_APP_PORT) || 3000
},
db: {
host: process.env.DEV_DB_HOST || 'localhost',
port: parseInt(process.env.DEV_DB_PORT) || 27017,
name: process.env.DEV_DB_NAME || 'myDB',
},
imagePath: "./profileImages/",
LogFillePath: "logs/combined.log",
ErrorFilePaht: "logs/error.log",
JwtSecret: process.env.JWT_SECRET
};
const prod = {
app: {
port: parseInt(process.env.PROD_APP_PORT) || 9000
},
db: {
host: process.env.PROD_DB_HOST || 'localhost',
port: parseInt(process.env.PROD_DB_PORT) || 27017,
name: process.env.PROD_DB_NAME || 'myDB'
},
imagePath: "./profileImages/",
LogFillePath: "logs/combined.log",
ErrorFilePaht: "logs/error.log",
JwtSecret: process.env.JWT_SECRET
};
const config = {
dev,
prod
};
module.exports = config[env];
I have this given module in config.js. I want to include this is my index.js. I tried multiple ways but config variable is always undefined.
I tried like this.
Try something like this for your config.js:
require("dotenv").config();
const dev = {
// ...
};
const prod = {
// ...
};
const configs = {
dev,
prod,
};
const config = configs[process.env.NODE_ENV];
if (!config) throw new Error("No valid configuration found, ensure your NODE_ENV is properly set");
module.exports = config;
Then you can simply
const config = require('./config');
I am able to connect to Heroku PostgreSQL after deploying in Heroku, but not Unable to connect to Heroku PostgreSQL from locally. It was working till yesterday. Using mac machine.
env.js
import dotenv from 'dotenv';
dotenv.config();
export default {
database_url: process.env.DATABASE_URL,
test_database_url: process.env.TEST_DATABASE_URL,
secret: process.env.SECRET,
port: process.env.PORT || 5000,
environment: process.env.NODE_ENV,
twoFactorAPIKey: process.env.TWOFACTOR_API_KEY
}
pool.js
import { Pool } from 'pg';
import env from '../../../env';
const databaseConfig = { connectionString: env.database_url };
const pool = new Pool(databaseConfig);
export default pool;
When is try with postman getting below screen:
note* I had installed NVM yesterday https://github.com/nvm-sh/nvm/blob/master/README.md#installing-and-updating
Resolved this issue by updating pg "pg": "^8.3.2", and node v14.8.0
I am trying to set the environment variable NODE_ENV for my project.
I am using Windows and have set the NODE_ENV in the system settings - this has been verified by typing SET and identifying for the row below in the output.
NODE_ENV=production
I cannot seem to get the variable to set in webpack though.
When adding the code below to my project (index.js) it only logs out undefined
console.log('PROCESS', process.env.NODE_ENV)
My webpack config:
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
process.env.NODE_ENV = process.env.NODE_ENV || 'development'
if (process.env.NODE_ENV === 'test') {
require('dotenv').config({ path: '.env.test' })
} else if (process.env.NODE_ENV === 'development') {
require('dotenv').config({ path: '.env.development' })
} else if (process.env.NODE_ENV === 'production') {
require('dotenv').config({ path: '.env.production' })
} else {
require('dotenv').config({ path: '.env.development' })
}
module.exports = (env) => {
const isProduction = env === 'production';
...
plugins: [
CSSExtract,
new UglifyJSPlugin(),
new webpack.DefinePlugin({
'process.env.FIREBASE_API_KEY': JSON.stringify(process.env.FIREBASE_API_KEY),
'process.env.FIREBASE_AUTH_DOMAIN': JSON.stringify(process.env.FIREBASE_AUTH_DOMAIN),
'process.env.FIREBASE_DATABASE_URL': JSON.stringify(process.env.FIREBASE_DATABASE_URL),
...
}),
devtool: isProduction ? 'source-map' : 'inline-source-map',
...
I have read this question, but still cannot get the env variable to set.
Where am I going wrong?
I managed to get set the NODE_ENV by using the cross-env package!
If you are developing node.js on Windows this can be very useful. Linux/Mac users would not have this problem.
To set the environment variable simply type
cross-env NODE_ENV=production [your commend goes here]
Example:
cross-env NODE_ENV=production webpack --env production