Overview
When you develop and run code on your machine, you run code in its development
environment.
Most companies will have a testing
environment similar to production; it has the same versions of software and runs on similar, albeit weaker, hardware. They do this to mitigate the risks when moving to production
servers that clients use.
Ideally, all environments run on the same stack, platforms, and versions. Still, it is common to have developers on the Windows platform with the latest version of Node.js and the production
server running on Linux with the last stable version of Node.js.
Environment Variables
Environment variables are a way to store configuration values that might change between environments. Common examples include:
- Port numbers
- Database connection strings
- API keys
- Feature flags
Using dotenv
The dotenv
package is commonly used to load environment variables from a .env
file:
// it's recommended to load configuration for .env as early as possible
require('dotenv').config(); // add this line as the first thing to run
// server code...
// we'll read the port from the server environment if it is there
// Heroku for example will have the PORT environment variable set already
const port = process.env.PORT || 9000;
// we can now use that port, use 9000 as a default if not set
server.listen(port, () => {
console.log(`\n*** Server Running on http://localhost:${port} ***\n`);
});
Best Practices
- Add
.env
to.gitignore
to prevent secrets from being committed - Provide a
.env.example
file with dummy values for documentation - Use sensible defaults for development
- Validate required environment variables at startup
- Never hardcode configuration values directly in your code
Steps to Implement
- Install the dotenv package:
npm install dotenv
- Add the require statement at the top of your entry file
- Create a
.env
file in your project root - Add your environment variables in KEY=VALUE format
- Access variables in your code using
process.env.VARIABLE_NAME
Challenge
Extract all secrets and values that need to change between development
and production
environments.