npm dotenv environment variables not recognized in nodejs module - node.js

Here is my project structure:
package.json:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon $NODE_DEBUG_OPTION server/boot.js --exec babel-node",
"start": "nodemon server/boot.js --exec babel-node",
"build": "babel server -d dist/server",
"serve": "node dist/server/boot.js"
},
The main file is server/boot.js:
import dotenv from 'dotenv';
import path from 'path';
dotenv.load({path: path.join(__dirname, '.env')});
import _ from 'underscore';
import configs from './config/index';
The server/config/index.js is only a barrel file that imports the other config files:
import app from './app';
import database from './database';
export default Object.assign({}, app, database);
In each of the config files I am not able to access any properties of the process.env object that are defined in the .env file.
Here is one of the config files for reference:
export default {
app: {
host: process.env.HOST || 'localhost',
port: process.env.PORT || 9000,
}
}
Here process.env.HOST is undefined, but the key is present in the .env file.
What I am doing wrong?

process.env object that are defined in the .env file.
Can you please be more specific about the process.env file?
As per https://www.npmjs.com/package/dotenv#rules the file should be in the format:
VAR1=value1
VAR2=value2
and not in
export default {
VAR1: 'value1',
VAR2: 'value2'
}

Related

SET dotenv env in package.json not work Linux ubuntu?

This is my Setting in package.json
"scripts": {
"start": "node backend/server.js",
"dev": "set NODE_ENV=DEVELOPMENT& nodemon backend/server",
"prod": "set NODE_ENV=PRODUCTION& nodemon backend/server"
},
This is my server.js looks like
const app = require('./app')
const dotenv = require('dotenv')
//dotenv path
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}`
)
})
My config.env looks like
PORT = 4000
NODE_ENV = DEVELOPMENT
I Use nodemon,... and i set node_env variable like in package.json
so, when i called
npm run dev : development
npm run prod : production
but when i run npm run prod. i still got server started on PORT 4000 in Development.
Is there any error in my code ?
Try removing the SET command as well as the & If on Linux:
"dev": "NODE_ENV=DEVELOPMENT nodemon backend/server",
"prod": "NODE_ENV=PRODUCTION nodemon backend/server"

Invalid connection string - process.env

I want to use process.env
-this is db.js-
import * as dotenv from "dotenv";
import mongoose from "mongoose";
dotenv.config();
const { DB_URL } = process.env.PRODUCTION ? process.env : "localhost:27017/save-idiot";
const { DB_PROTOCOL } =process.env.PRODUCTION ? process.env : "mongodb"
mongoose.connect(`${DB_PROTOCOL}://${DB_URL}`, {
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true
});
const db = mongoose.connection;
const handleOpen = () => console.log("✅ Connected to DB");
const handleError = error => console.log(`❌ Error on DB Connection:${error}`);
db.once("open", handleOpen);
db.on("error", handleError);
-package.json-
"scripts": {
"dev:server": "nodemon --exec babel-node src/init.js -- delay 2",
"dev:assets": "cd src && WEBPACK_ENV=development webpack -w",
"lint": "eslint src/",
"fix": "eslint --fix src/",
"clean": "rm -rf build",
"build:server": "babel src --out-dir build --ignore 'src/assets','src/static','src/webpack.config.js'",
"build:assets": "cd src && WEBPACK_ENV=production webpack",
"copy:static": "cp -R src/static src/views build/",
"build": "npm run clean && npm run lint && npm run build:server && npm run build:assets && npm run copy:static",
"start": "PRODUCTION=true forever start build/init.js"
}
const { DB_URL } = process.env.PRODUCTION ? process.env : "localhost:27017/save-idiot";
const { DB_PROTOCOL } =process.env.PRODUCTION ? process.env : "mongodb"
if I npm run dev:server,
I want to get "localhost:27017/save-idiot" & "mongodb"
and if I npm start,
I want to get process.env
How can I do this?
You could use cross-env package, it is used to set environment variables.
Once you've installed it, you could try like this:
"start": "cross-env PRODUCTION=true forever start build/init.js"
Try use
dotenv.config({ path: '.env' });
For configure many environments you can use envdist

i have an issue accessing env variables in NodeJS

Well, i have 3 types of environments (i.e development,test,production) am using nodejs with express. My problem is this my either development and production scripts don't run because they can't access .env variables i have searched online but i can't find something helpful. This is what i did i created .env file and put my variables in. i tried using export command i.e export key=value. please help
I created a .env file and added either of development database url and production database url, but when i run either of environment it doesn't work. i also tried using export command export key=value. but it works for a while and then it fails again.
//my config
require('dotenv').config();
module.exports ={
development :{
use_env_variable: process.env.DEVELOPMENT_URL,
dialect: 'postgres'
},
production :{
use_env_variable:process.env.PRODUCTION_URL,
dialect: 'postgres',
}
}
//my package.json scripts
{
"name": "report_deck",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "export NODE_ENV=production && sequelize db:migrate && node ./build/index.js",
"dev": "nodemon --exec babel-node ./api/index.js",
"test": "export NODE_ENV=test && sequelize db:migrate:undo:all && sequelize db:migrate && nyc --require #babel/register mocha ./api/test/test.js --timeout 20000 --exit",
"build": "rm -rf ./build && babel -d ./build ./api -s",
"generate-lcov": "nyc report --reporter=text-lcov > lcov.info",
"coveralls-coverage": "coveralls < lcov.info",
"codeclimate-coverage": "codeclimate-test-reporter < lcov.info",
"coverage": "nyc npm test && npm run generate-lcov && npm run coveralls-coverage && npm run codeclimate-coverage"
},
}
//.env
DEVELOPMENT_URL=postgres://example1:pass#example:5432/dbname
PRODUCTION_URL=postgres://example2:pass#example:5432/dbname
//my index.js
import express from 'express';
import bodyParser from 'body-parser';
import classRoutes from './server/routes/classRouter';
// all routes
import cors from 'cors';
const app = express();
app.use(bodyParser.json());
app.use(cors());
//use all routes
app.use(bodyParser.urlencoded({ extended: false }));
const port = process.env.PORT || 8003;
app.get('*', (req, res) => res.status(200).send({
message: "Entrance"
}));
app.listen(port, () => {
console.log("Entrance done, We are running at port " + port);
});
export default app;
Expectations:
It should log "entrance done we are running on port 8003" for (npm run dev)
It should log "entrance done we are running on port 5000" for(heroku local web)
Actual:
throw new TypeError('Parameter "url" must be a string, not ' + typeof url);
You should add -r dotenv/config to your starting script to preload dotenv =>
"start": "export NODE_ENV=production && sequelize db:migrate && node -r dotenv/config ./build/index.js",
Check docs

How can I start an Express app using Now?

When deploying to Now, I'm trying to build and start an Express server. It's currently building, but not starting the server.
My package.json looks like this, am I missing anything?
"scripts": {
"dev": "node server.js",
"build": "next build && cross-env NODE_ENV=production node server.js",
"start": "cross-env NODE_ENV=production node server.js",
"export": "next build && next export"
}
I have a file called /utilities/app.ts where I setup my common express configuration (this is what I use but you can add/remove things as needed):
import express from 'express';
import helmet from 'helmet';
import { commonMiddlewares } from '../middlewares'
const expressApp = express();
expressApp.use(helmet());
expressApp.set("trust proxy", 1);
expressApp.use(...commonMiddlewares);
export const app = expressApp;
Then in the api endpoint where I want to use express I import this utility:
import { app } from "../utilities/app";
import { Request, Response } from "express";
app.get("*", async (req: Request, res: Response) => { ... })

How to --watch uncompressed files (without Webpack)

I have worked code, which is built in /dist by webpack, for developming that is slow to wait for updating/building in dist/ folder and get result form it also. there is good "webpack-dev-server --port=4200" command but I have expressJS. How I can get updating result fast after run project. Maybe It is possable via webpack or not:
/////////////////////package.json
"scripts": {
"ng": "ng",
"dev": "concurrently nodemon ./src/index.ts \"tsc -w -p ./src\" ",
"start": "ng build && concurrently nodemon ./src/index.ts \"tsc -w -p ./src\" ",
"build": "ng build --watch",
"build:watch": "\"tsc -w -p ./src\"",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
//////////////////////index.ts
import * as express from 'express';
import { join } from 'path';
import { json, urlencoded }from 'body-parser';
var app : any = express();
app.use(express.static(join(__dirname + '/../dist')));
app.use(json());
app.use(urlencoded({
extended: true
}));
app.get('*', function(req, res, next) {
res.sendFile(join(__dirname + '/../dist/index.html'));
});
console.log('3000!! ', 3000);
app.listen(process.env.PORT || 3000);
I tried just to include ./src folder - app.use(express.static(resolve(__dirname, '../src'))); res.sendFile(resolve(__dirname, '../src/index.html')); but it is not working:
Help Please
packaje.json
dist
assets
src - app
- index.html
- index.ts

Resources