I'm developing a little server made in node, hapijs, nodemon, etc.
It's a basic api rest which will grow with ongoing dev.
I need to have different variables for dev. and production. I actually have only one .env file. I've read it is not recommended to have 2 separate files for this.
How should I modify my app.js to have two situations?
Thanks a lot in advance,
As you've probably already done. Write your code to use environment variables. (whether you run locally or on production, that's the same code.).
const ACCESS_KEY = process.env.ACCESS_KEY;
Your .env file then contains ONLY your local settings, for debug on your local computer. You can add .env in your .gitignore file to make sure it doesn't get pushed to your git repository.
Production settings by contrast shouldn't be in any file at all. They should only be configured directly in the settings of your cloud provider.
It's possible to do this from the "Settings" tab in your heroku app dashboard. There is a section "Config vars".
When heroku launches your application, it will define the configured config variables as environment variables. And you will be able to access them with process.env just as you would with the environment variables which were defined in your .env file during development.
The dashboard makes it easy to get an overview and to manage the keys. Perhaps even more conveniently, you can also do this with the heroku cli tool straight from the commandline.
To get a list of your current environment variables, run.
heroku config
To add a new key from the CLI.
heroku config:set ACCESS_KEY=adfsqfddqsdf
All of this is also described in the official documentation of Heroku.
Generally, you would generate your env file at build time. For example, using AWS SSM / or some kind of Vault that is secure, you store your secrets like db passwords. The env file is a template that gets compiled with the right env vars for the target deployment.
Also, you can have dummy variables in your env template that you commit to git. Then add a .gitignore file with an entry to your env template to ensure you don't commit any secrets to the env file. Then locally you compile your file for local, during your staging build for staging, during prod build for prod, etc.
As the app gets larger, this allows you to provision credentials per person / per environment. You add the associated secrets / permissions to the vault. Allow the people/environments access to those secrets, and then you can control access in a pretty fine grained fashion.
I suggest using an npm package for handling different environments variables and keys. (or implement it by yourself)
Alongside with .env file
1- use .env file to store credentials and secrets 2- Reference these .env variables via different package that provides separate file for each environment
suggested package : https://www.npmjs.com/package/config
I used this approach in one of my projects and made my life easier.