What is the config library?
The config library is a popular Node.js module designed for managing application configurations. It allows you to store settings in separate files (JSON, YAML, JS) and automatically load them depending on the environment (development, production, staging). This eliminates the need to hardcode parameters such as API keys, server ports, or database connection strings.
Why is it needed?
In real projects, configuration often changes: locally you use one database URL, on the server another. Without the config module, you would have to manually change variables or use complex constructs with process.env. The library simplifies this process: it automatically selects a file based on the NODE_ENV environment variable (e.g., development.json or production.json).
How to install?
Install the module via npm:
npm install configMain features
- Automatic environment detection: by default, it looks for the
default.jsonfile, then{NODE_ENV}.json. - Format support: JSON, YAML, JS, TOML.
- Deep nesting: access nested fields using dot notation (
config.get('database.host')). - Security: sensitive data (passwords) can be hidden via environment variables.
Code example in JavaScript (Node.js)
Create the folder structure:
project/
├── config/
│ ├── default.json
│ └── production.json
├── app.js
└── package.jsonconfig/default.json:
{
"server": {
"port": 3000
},
"database": {
"host": "localhost",
"port": 5432
}
}config/production.json:
{
"server": {
"port": 80
},
"database": {
"host": "prod-db.example.com"
}
}app.js:
const config = require('config');
// Get the server port
const port = config.get('server.port');
// Get the database host
const dbHost = config.get('database.host');
console.log(`Server running on port ${port}`);
console.log(`Database host: ${dbHost}`);
// Start the server
const http = require('http');
http.createServer((req, res) => {
res.end('Hello World');
}).listen(port);Run with different environments:
# Default (development)
node app.js
# Server running on port 3000
# Production
NODE_ENV=production node app.js
# Server running on port 80When to use?
The config library is ideal for medium and large Node.js applications that require separating settings by environment. It is indispensable when deploying to multiple servers, in a microservice architecture, and when working with confidential data (via environment variables). For small projects or scripts, you can get by with simple process.env, but config makes the code cleaner and more scalable.