Node.js Spring Cloud Config Client
The `cloud-config-client` library provides a Node.js implementation for connecting to and consuming configuration from a Spring Cloud Config Server. Currently at version 1.6.2, it enables Node.js applications to fetch dynamic configurations, supporting application names, profiles, and labels as defined by the Spring Cloud specification. It handles property resolution based on Spring's hierarchy rules and offers a simple API for retrieving values by key, including context-based substitutions. The library provides both Promise-based and Node.js-style callback interfaces for configuration loading and ships with TypeScript types for enhanced developer experience. It differentiates itself by offering a direct, opinionated integration with the Spring Cloud Config ecosystem within Node.js environments, rather than a generic key-value store client.
Common errors
-
Parameter 'application' is deprecated. Use 'name' instead.
cause Using the deprecated `application` parameter in `client.load()` options.fixReplace `application` with `name` in the `client.load()` options: `{ name: 'your-app-name' }`. -
Error: self-signed certificate in certificate chain
cause Attempting to connect to a Spring Cloud Config Server over HTTPS with a self-signed or untrusted certificate, while `rejectUnauthorized` is true (default).fixFor development/testing, set `rejectUnauthorized: false` in the `client.load()` options. For production, ensure a valid, trusted certificate is used or properly configured on the server. -
Config server responded with 401 Unauthorized
cause Missing or incorrect basic authentication credentials for accessing the Spring Cloud Config Server.fixProvide correct `auth` object in `client.load()` options (e.g., `{ auth: { user: 'username', pass: 'password' } }`) or embed credentials directly in the `endpoint` URL (`http://user:pass@localhost:8888`). -
TypeError: client.load is not a function
cause Incorrectly importing the `client` object, e.g., using named import syntax for a default export in CommonJS or destructuring directly.fixFor CommonJS: `const client = require('cloud-config-client');`. For ESM/TypeScript: `import client from 'cloud-config-client';`.
Warnings
- deprecated The 'application' parameter in `client.load()` options is deprecated. It may be removed in a future major version.
- gotcha By default, the client rejects unauthorized (self-signed) SSL certificates when connecting to the Spring Cloud Config Server over HTTPS. This can cause connection issues in development environments or with custom certificate authorities.
- gotcha The library requires Node.js version 10 or higher. Running on older Node.js versions may lead to unexpected errors or unsupported syntax, particularly with async/await and newer language features.
- gotcha Context references in configuration properties (e.g., '${KEY:DEFAULT}') are a simple string substitution mechanism and do NOT support Spring Expression Language (SpEL) features. Attempting to use SpEL syntax will not work as expected.
Install
-
npm install cloud-config-client -
yarn add cloud-config-client -
pnpm add cloud-config-client
Imports
- client
import { client } from 'cloud-config-client';import client from 'cloud-config-client';
- client
const { load } = require('cloud-config-client');const client = require('cloud-config-client'); - Config
import { Config } from 'cloud-config-client';
Quickstart
import client, { Config } from 'cloud-config-client';
import * as https from 'https';
async function fetchConfig() {
try {
// Ensure CONFIG_SERVER_URL, CONFIG_USERNAME, CONFIG_PASSWORD are set in environment
const config: Config = await client.load({
endpoint: process.env.CONFIG_SERVER_URL ?? 'http://localhost:8888',
name: 'my-application', // 'application' is deprecated, use 'name'
profiles: ['development', 'aws'],
label: 'main',
auth: {
user: process.env.CONFIG_USERNAME ?? 'configuser',
pass: process.env.CONFIG_PASSWORD ?? 'configpassword'
},
// Reject unauthorized (self-signed) certificates in production, allow in dev
rejectUnauthorized: process.env.NODE_ENV === 'production',
// Provide environment variables as context for placeholder substitution
context: {
...process.env,
APP_VERSION: '1.0.0' // Custom context value
},
headers: {
'X-Trace-ID': 'my-app-trace-123'
},
agent: process.env.HTTPS_PROXY ? new https.Agent({ proxy: process.env.HTTPS_PROXY }) : undefined
});
console.log('Configuration loaded successfully!');
const databaseUrl = config.get('database.url');
console.log(`Database URL: ${databaseUrl}`);
const welcomeMessage = config.get('app.message', 'key01'); // Example with prefix
console.log(`Welcome Message: ${welcomeMessage}`);
// Iterate over all properties (excluding overridden by default)
console.log('\nAll properties:');
config.forEach((key, value) => {
console.log(` ${key}: ${value}`);
});
// Access raw properties if needed
// console.log('\nRaw config properties:', config.raw);
} catch (error: any) {
console.error('Failed to load configuration:', error.message);
if (error.response) {
console.error('Server response status:', error.response.status);
}
}
}
fetchConfig();