We all write applications in a development environment and deploy them in the production environment on our servers. Now it is not only the terms or operating systems which get changed in development or production environment, instead quite a few other things get changed. For example:
In the development environment, you will use your personal email to send emails, whereas in production you may use the company email. Same holds true for 3rd party services API keys.
During development, you may not want to cache the views, whereas in production views caching is required for performance.
There are a couple of ways of dealing with the complexity of the environment switch.
if/else clauses inside your app and check for the current env, before taking the action.
Create multiple copies of
configuration files for each environment.
To overcome this problem AdonisJs makes use of Environment variables, which are very common in bash scripts and now also used by modern frameworks across different communities.
There is a
.env file inside the root of every brand new AdonisJs project. The purpose of this file is to keep all the configuration variables, which are supposed to change across environments. Following is the default .env file.
This file is autoloaded at the time of booting the HTTP server or running Ace commands. You can read values from this file with the help of
Env provider or access them using the Node.js
Values from this file are accessible via
process.env or by using inbuilt Env provider. Ideally, it is recommended to use the Env provider since it may handle some inconsistency for you.
get method will return the value of an environment variable. Also it accepts an optional
defaultValue, which is returned when the actual value is
const Env = use('Env')
set method will update the existing value with the new value. Also, it will create the key/value pair if it does not exist.
const Env = use('Env')
Updating environment variables after a certain part of the application have read them has no effect. It is recommended to override env variables via command line when starting the HTTP server. For example:
PORT=8000 npm start.
AdonisJs will automatically load the
.env file from the root of your project. You can override the location of the file by defining a different path at the time of starting the server.
ENV_PATH=/etc/config/.env npm start
At times you may set env variables using your hosting provider dashboard. In that case having
.env file makes no sense and to ignore the Env provider error, you must start the server with
ENV_SILENT=true npm start