How do you detect the environment in an express.js app? - javascript

How do you detect what environment an expressJS app is running in? (development, test, production?). There's nothing in process.env indicating an environment...
I'm aware that you can declare variables in your configuration file under each environment, but that doesn't help if you are dynamically loading modules...

You can either check the environment by checking the app.settings.env (this will work in Express), or you can do it in a more direct way by checking process.env.NODE_ENV (the environment is the one found in that variable or 'development' by default < this also works in other libraries such as Socket.IO etc).

app.get('env') would also return the environment.
if ( app.get('env') === 'development' ) {
app.use(express.errorHandler());
}

I'd like to address a straightforward way to passing NODE_ENV variables to your node script in order to access them in process.env
"scripts": {
"start": "./node_modules/.bin/cross-env NODE_ENV=development ./node_modules/.bin/nodemon server.js",
"debug": "./node_modules/.bin/cross-env NODE_ENV=development ./node_modules/.bin/nodemon --debug server.js",
"test": "./node_modules/.bin/cross-env NODE_ENV=test ./node_modules/.bin/babel-tape-runner test/test-*.js"
},
can be used as
if ( app.get('env') === 'development' ) {
app.use(express.errorHandler());
}

The can detect which environment you are in by inspecting app.settings.env.

cannot access the nodejs server. can detect node env from express using app.setting.env
var app = express();
app.setting.env render to the template engine.
check from the browser.

There are a lot of useful recommendations in other answers. I'm generally doing it like this:
const environment = process.env.NODE_ENV || 'development';
The good thing is that such approach is not specific to Express per se, but actually is an accepted practice in wider Node.js ecosystem.
Also, I've implemented a reusable module, which allows to automatically detect environment by analyzing both CLI arguments and NODE_ENV variable. This could be useful on your development machine, because you can easily change environment by passing a CLI argument to you Node.js program like this: $ node app.js --prod.
Please see more details and use cases on the detect-environment's page.

Related

How to use Azure Pipeline variable in JavaScript (React) project?

How do I use variable defined for the pipeline in React Project?
Currently, I have build variable defined in the .yml file like that
variables:
src: "virtual-furnace-app"
dest: "$(src)/build"
REACT_APP_VERSION: $(Build.BuildNumber)
and in the front end code, I have tried to accessing it like that but it is undefined
export const REACT_APP_VERSION = process.env.NODE_ENV === "development" ? `v${pjson.version} (Development build)` : `v${pjson.version} (${process.env.REACT_APP_VERSION})` ;
After while I found solution myself.
So in the code, I check if we are on localhost NODE_ENV === development and if not I will read variable injected to React script process.env.REACT_APP_VERSION
import pjson from "../../package.json"
export const REACT_APP_VERSION = process.env.NODE_ENV === "development" ? `v${pjson.version} (Development build)` : `v${pjson.version} (${process.env.REACT_APP_VERSION})` ;
Azure Pipeline yml code
REACT_APP_VERSION=$(BuildID) yarn build
How to use Azure Pipeline variable in JavaScript (React) project?
You could try to use a .env file to store the variables, then use them in a React Native app.
You can reference this blog for details : How to gracefully use Environment Variables in a React Native app.
Also find some similar threads in SO, you can reference them can check if that helps:
Azure Devops Variable Substitution for Frontend js applications
How to use environment variables in React app hosted in Azure
Besides, you could also try to set REACT_APP_VERSION in the start of your script as well, e.g. "scripts": { "start": "cross-env REACT_APP_VERSION=$REACT_APP_VERSION react-scripts start" }

How to send environment variables to Jest CLI?

I have a script that runs a Jest test for me, and I want to set an environment variable before running it, something like this:
my_test_script.sh
IMPORTANT_ENV_VAR=value_that_matters
./node_modules/.bin/jest --useStderr ./__tests__/my.test.js
However, inside "my.test.js" the IMPORTANT_ENV_VAR is not set when I run my test like this.
How do I pass the environment variable into the Jest CLI ?
What i do to solve the problem is ugly, but works.
I'm searching for a better solution (Simply set a Environment Variable by cli), not able to find it.
i create a js file that set the environment variable and i load that file passing it to the setupFile cli command. for example
jest --setupFile=setter.js
and setter.js contains
process.env.A = "B"
so, before running each test, i can read the process.env.A variable.
Use cross-env:
{
"scripts": {
"build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"
},
"devDependencies": {
"cross-env": "7.0.3",
}
}
Its purpose is exactly to pass environment variables to an npm script in a cross-platform way.
Going off of #Andrea Bisello's answer, you can load the environment variables from a plain JavaScript file. This is the key take-away.
So, in my environment, I already had a jest.config.ts. Since I was already using a .env file for defining my environment variables (located at the root of my project), I just needed a way to load them when running jest from a CLI at the root of my project.
Doing that is very simple; just add this to the jest.config.ts or jest.config.js:
// jest.config.{ts,js}
const { config } = require('dotenv');
config();
Then, from the root of your repo, you can do something like:
npx jest
Because it's hard to set environment variables in a platform-independent way under npm/package.json, and because jest --setupFiles, while in the usage, isn't in the docs and doesn't seem to work (24.9), jest REALLY DOES need a --envVar option to support environmental overrides external to package.json (like dev/production).
Whoops!
Not a Jest problem, I just needed to export in the shell script :
export IMPORTANT_ENV_VAR=value_that_matters
./node_modules/.bin/jest --useStderr ./__tests__/my.test.js
If you are using npm, you can add this to your package.json to define environment variables in the testing env.
"jest": {
"globals": {
"ENVVAR1": true,
"ENVVAR2": "value"
}
}

How does Node set its environment variable?

When running a Node application, how does Node know what environment it is running in?
I understand that the environment is defined within process.env.NODE_ENV, but how and where is that variable defined?
There multiple ways of setting node variables but most common
1. is to start your console with them enabled as following:
> NODE_ENV=prod node start.js
process.env.NODE_ENV // prod
But there are times when you can explicitly set the env before the start of the file:
process.env.NODE_ENV = 'test';
require('config') // then it will return me the test.json config
// I use this technique mostly for unit tests
2. export the envars in the package.json
"scripts": {
"start": "export NODE_ENV=dev && node server.js", // for linux
"start": "set NODE_ENV=dev && node server", // for windows
"test": "mocha"
},
When you run npm start the script will run the server in dev mode
3. use a npm package as dotenv and setup a .env file
Plugins for env management as dotenv the most common used one. Where you can create .env files with needed ENV variables
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
These usually are set in package.json commands or come from a .env file.
For example, NODE_ENV=development from a .env file can be accessed in process.env.NODE_ENV.
For loading .env files into process.env check out dotenv.
The variable isn't defined unless you define it.
I guess you are using a regular Windows machine.
On Windows you can simply do this.
create a random index file and put this in it: console.log(process.env.NODE_ENV)
and then run it with: set NODE_ENV=productionEnvironment && node index

can'f find the "process.env.NODE_ENV"

The variable process.env.NODE_ENV always bothers me every time I see it in a config file, especially webpack.config.js. Where can I find this? Because sometimes I want to change it's value to production instead of development.
You can set any environmental variable like NODE_ENV while running your applications.
Linux/Mac
NODE_ENV=production node myapp.js
Windows/Powershell
$env:NODE_ENV="production" ; node myapp.js
You can access environmental variable NODE_ENV inside your myapp.js by
process.env.NODE_ENV
process.env.NODE_ENV is Node.js environment.
With the help of this mostly we decide our deployment environment in which we are deploying the code.
It can be development,stag or production.
We can do other stuff on env, it's up to us.
to set in Linux
export NODE_ENV=production
on Windows
set NODE_ENV=production
Example
config.js
{development:{
//your `env` value
},
production:{
//Your `env` value
}}
Now on the basis of NODE_ENV your env will be set

app.get('env') usage in localhost and production

var express = require('express');
var app = express();
var db_url;
if(app.get('env') == "development"){
db_url = 'mongodb://127.0.0.1:27017/localhost';
}else{
db_url = 'something else';
}
console.log(app.get('env'));
What does app.get('env') in express means? I'm seeing it still print development when I deploy my code to live server.
You need to tell it you're in production mode; see part of the Express docs.
In development, you typically set environment variables in your interactive shell, for example by using export or your .bash_profile file. But in general you shouldn’t do that on a production server; instead, use your OS’s init system (systemd or Upstart). The next section provides more details about using your init system in general, but setting NODE_ENV is so important for performance (and easy to do), that it’s highlighted here.
With Upstart, use the env keyword in your job file. For example:
# /etc/init/env.conf
env NODE_ENV=production
For more information, see the Upstart Intro, Cookbook and Best Practices.
With systemd, use the Environment directive in your unit file. For example:
# /etc/systemd/system/myservice.service
Environment=NODE_ENV=production
For more information, see Using Environment Variables In systemd Units.
If you are using StrongLoop Process Manager, you can also set the environment variable when you install StrongLoop PM as a service.
You can also set process.env.NODE_ENV in a JavaScript file if necessary.

Categories

Resources