HOWTO · Node.js

How to Create and Store Configurations in Node.js

This tutorial demonstrates how to create and store configurations in Node.js.

On this page

A centralized configuration keeps settings such as ports and database hosts out of application logic. The npm package config loads configuration for a Node.js app and gives code one place to read those settings. Start with a default file, then add environment-specific files when development, testing, staging, and production need different values. The examples below use JSON and do not require Express.

Install node-config to Create and Store Configurations in Node.js

From your project directory, install the npm package named config with npm install config. npm records it in package.json, so the dependency is available when the project is installed elsewhere. The package name is config; node-config is a common shorthand, not the name to pass to npm.

Create config/default.json for values shared by the app. JSON requires double-quoted property names and string values. For example, the file can contain {"server":{"port":3000},"db":{"host":"localhost","port":27017,"name":"mongodb"}}. Keep secrets out of files committed to source control; inject credentials through the deployment environment or a secret manager.

Run this example:

const defaults = {
  server: { port: 3000 },
  db: { host: "localhost", port: 27017, name: "mongodb" }
};

console.log(defaults.server.port, defaults.db.host);
3000 localhost

This standalone JavaScript example completes successfully with the output 3000 localhost. In your app, load the package with const config = require("config") and read a value with config.get("server.port"); use the same pattern for db.host. The code example above uses JavaScript objects only to make the property path clear; the configuration file itself remains JSON.

For an environment-specific setup, add a file such as config/production.json with only the values that differ from the defaults. Set NODE_ENV to identify the deployment environment when starting the app. NODE_CONFIG is the package’s environment variable for supplying configuration overrides. For the installed version’s exact NODE_CONFIG syntax, consult the official environment-variable guidance; for file-loading precedence, see the official configuration-files guidance.

Use valid JSON in each .json file and keep the configuration format consistent. The file names and values above are examples; adapt them to your app’s settings. YAML, JSON5, and HJSON support can depend on the package version and setup, so verify format support before using those formats. A basic setup needs only package.json, config/default.json, and application code that reads settings through config.get.