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
Related
Hopefully, this will be my last question regarding NextJS.
I finally moved all of my React components to NextJS and I'm in the step of uploading it to Heroku.
The usual code for a React app looks like this:
if (
process.env.NODE_ENV === 'production' &&
process.env.NODE_TECHNOLOGY === `react`
) {
// This is for ReactJS
app.use(express.static(path.join(path.resolve(), 'client-app/build')))
app.get('*', (req, res) =>
res.sendFile(
path.resolve(path.resolve(), 'client-app', 'build', 'index.html')
)
)
} else {
app.get('/', (req, res) => {
res.status(200).json({
success: true,
data: 'API is running',
time: new Date().toISOString(),
})
})
}
I then tried adding an else-if statement for NextJS:
if (
process.env.NODE_ENV === 'production' &&
process.env.NODE_TECHNOLOGY === `react`
) {
// This is for ReactJS
app.use(express.static(path.join(path.resolve(), 'client-app/build')))
app.get('*', (req, res) =>
res.sendFile(
path.resolve(path.resolve(), 'client-app', 'build', 'index.html')
)
)
} else if (
process.env.NODE_ENV === 'production' &&
process.env.NODE_TECHNOLOGY === `next`
) {
app.use(express.static(path.join(path.resolve(), 'client-next-app/build')))
app.get('*', (req, res) =>
res.sendFile(
path.resolve(path.resolve(), 'client-next-app', 'build', 'index.html')
)
)
} else {
// This is for NextJS production
app.get('/', (req, res) => {
res.status(200).json({
success: true,
data: 'API is running',
time: new Date().toISOString(),
})
})
}
However, I'm still unsure what I am supposed to submit because after running the npm run build command, next returns this file structure:
I already modified my nextJS package.json file:
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start -p $PORT"
},
and this is what my top-folder package.json file looks like:
"scripts": {
"client-install": "npm install --prefix client",
"start": "NODE_ENV=production node server.js",
"server": "nodemon server.js",
"client-react": "npm start --prefix client-app",
"client-next": "npm run dev --prefix client-next-app",
"devreact": "concurrently \"npm run server\" \"npm run client-react\" \"npx peer --port PORT\" ",
"dev": "concurrently \"npm run server\" \"npm run client-next\" \"npx peer --port PORT\" ",
"debug": "ndb server",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client-next-app && npm run build --prefix client-next-app"
},
Any idea? Thanks.
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"
Trying to configure proxy in react native with node to run axios calls.
Tried the following code in server/package.json
"proxy": {
"/*": {
"target": "http://localhost:5000/"
}
},
"scripts": {
"start": "node index.js",
"server": "nodemon index.js",
"client": "cd ../client && yarn ios",
"dev": "concurrently \"yarn server\" \"yarn client\""
}
server/authRouter.js
const authRouter = require('express').Router();
authRouter.get('/test', (req, res) => {
res.send('proxy success');
});
module.exports = authRouter;
server/index.js
const express = require('express');
const authRouter = require('./authRouter');
const app = express();
app.use('/auth', authRouter);
const PORT = process.env.PORT || 5000;
app.listen(PORT);
client/app.js
await axios.get('/auth/test');
When I run yarn dev and test an axios call, it logs the following error
LOG [Error: Network Error]
any help would be much appreciated.
Try calling the proxy directly in axios
http://localhost:5000/auth/test
I'm not sure why it doesn't work that way, even i had a problem in the past.
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
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