In this tutorial, you learn how to enable dynamic configuration in your JavaScript applications.
The example in this tutorial builds on the sample application introduced in the JavaScript quickstart.
Before you continue, finish Create a JavaScript app with Azure App Configuration.
Add the following key-value to your Azure App Configuration store. For more information about how to add key-values to a store using the Azure portal or the CLI, go to Create a key-value.
Key
Value
Label
Content type
message
Hello World!
Leave empty
Leave empty
Console applications
The following examples show how to use refreshable configuration values in console applications.
Choose the following instructions based on how your application consumes configuration data loaded from App Configuration, either as a Map or a configuration object.
Load data from App Configuration
You can connect to App Configuration using either Microsoft Entra ID (recommended) or a connection string. The following code snippet demonstrates using Microsoft Entra ID. You use the DefaultAzureCredential to authenticate to your App Configuration store. While completing the quickstart listed in the prerequisites, you already assigned your credential the App Configuration Data Reader role.
Open the file app.js and update the load function. Add a refreshOptions parameter to enable the refresh and configure refresh options. The loaded configuration will be updated when a change is detected on the server. By default, a refresh interval of 30 seconds is used, but you can override it with the refreshIntervalInMs property.
// Connecting to Azure App Configuration using endpoint and token credentialconst appConfig = await load(endpoint, credential, {
// Enabling the dynamic refresh
refreshOptions: {
enabled: true
}
});
The configuration object is constructed by calling constructConfigurationObject function.
To ensure an up-to-date configuration, update the configuration object in the onRefresh callback triggered whenever a configuration change is detected and the configuration is updated.
JavaScript
// Connecting to Azure App Configuration using endpoint and token credentialconst appConfig = await load(endpoint, credential, {
// Enabling the dynamic refresh
refreshOptions: {
enabled: true
}
});
// Constructing configuration objectlet config = appConfig.constructConfigurationObject();
// Setting up callback to ensure `config` object is updated once configuration is changed.
appConfig.onRefresh(() => {
config = appConfig.constructConfigurationObject();
});
Nóta
If you get the error: "Refresh is enabled but no watched settings are specified.", please update the @azure/app-configuration-provider package to version 2.0.0 or later.
Setting up refreshOptions alone won't automatically refresh the configuration. You need to call the refresh method to trigger a refresh. This design prevents unnecessary requests to App Configuration when your application is idle. You should include the refresh call where your application activity occurs. This is known as activity-driven configuration refresh. For example, you can call refresh when processing an incoming message or an order, or inside an iteration where you perform a complex task. Alternatively, you can use a timer if your application is always active. In this example, refresh is called in a loop for demonstration purposes. Even if the refresh call fails for any reason, your application will continue to use the cached configuration. Another attempt will be made when the configured refresh interval has passed and the refresh call is triggered by your application activity. Calling refresh is a no-op before the configured refresh interval elapses, so its performance impact is minimal even if it's called frequently.
Add the following code to poll configuration changes of watched key-values.
// Polling for configuration changes every 5 secondswhile (true) {
console.log(appConfig.get("message")); // Consume current value of message from a Map
appConfig.refresh(); // Refreshing the configuration setting asynchronouslyawait sleepInMs(5000); // Waiting before the next refresh
}
JavaScript
// Polling for configuration changes every 5 secondswhile (true) {
console.log(config.message); // Consume current value of message from an object
appConfig.refresh(); // Refreshing the configuration setting asynchronouslyawait sleepInMs(5000); // Waiting before the next refresh
}
Now the file app.js should look like the following code snippet:
Visit http://localhost:3000 and you will see the response:
Load data from App Configuration
Update the server.js to use App Configuration and enable dynamic refresh:
JavaScript
const http = require("http");
const { load } = require("@azure/app-configuration-provider");
const { DefaultAzureCredential } = require("@azure/identity");
const endpoint = process.env.AZURE_APPCONFIG_ENDPOINT;
const credential = new DefaultAzureCredential(); // For more information, see https://learn.microsoft.com/azure/developer/javascript/sdk/credential-chains#use-defaultazurecredential-for-flexibilitylet appConfig;
asyncfunctioninitializeConfig() {
appConfig = await load(endpoint, credential, {
refreshOptions: {
enabled: true,
refreshIntervalInMs: 15_000 // set the refresh interval
}
});
}
functionstartServer() {
const server = http.createServer((req, res) => {
// refresh the configuration asynchronously when there is any incoming request
appConfig.refresh();
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end(appConfig.get("message"));
});
const hostname = "localhost";
const port = 3000;
server.listen(port, hostname, () => {
console.log(`Server running at http://localhost:${port}/`);
});
}
// Initialize the configuration and then start the server
initializeConfig()
.then(() => startServer());
Request-driven configuration refresh
In most cases, the refresh operation of the App Configuration provider can be treated as a no-op. It will only send requests to check the value in App Configuration when the refresh interval time you set has passed.
We recommend implementing request-driven configuration refresh for your web application. The configuration refresh is triggered by the incoming requests to your web app. No refresh will occur if your app is idle, when there is no request incoming. When your app is active, you can use a middleware or similar mechanism to trigger the appConfig.refresh() call upon every incoming request to your application.
If a request to App Configuration for change detection fails, your app will continue to use the cached configuration. New attempts to check for changes will be made periodically while there are new incoming requests to your app.
The configuration refresh happens asynchronously to the processing of your app's incoming requests. It will not block or slow down the incoming request that triggered the refresh. The request that triggered the refresh may not get the updated configuration values, but later requests will get new configuration values.
Run the application
Relaunch your http server:
Console
node server.js
Visit http://localhost:3000 and verify the response which is the message key in your App Configuration store.
Update the following key-values to the Azure App Configuration store. Update value of the key message.
Key
Value
Label
Content type
message
Hello World - Updated!
Leave empty
Leave empty
After about 15 seconds, refresh the page for multiple times and the message should be updated.
Clean up resources
If you don't want to continue using the resources created in this article, delete the resource group you created here to avoid charges.
Tábhachtach
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Ensure that you don't accidentally delete the wrong resource group or resources. If you created the resources for this article inside a resource group that contains other resources you want to keep, delete each resource individually from its respective pane instead of deleting the resource group.
Sign in to the Azure portal, and select Resource groups.
In the Filter by name box, enter the name of your resource group.
In the result list, select the resource group name to see an overview.
Select Delete resource group.
You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm, and select Delete.
After a few moments, the resource group and all its resources are deleted.
Next steps
In this tutorial, you enabled your JavaScript app to dynamically refresh configuration settings from Azure App Configuration. To learn how to use an Azure managed identity to streamline the access to Azure App Configuration, continue to the next tutorial.
Change a JavaScript web app update mechanism from polling to real-time push-based architecture with SignalR Service, Azure Cosmos DB and Azure Functions. Use Vue.js and JavaScript to use SignalR using Visual Studio Code.
Build end-to-end solutions in Microsoft Azure to create Azure Functions, implement and manage web apps, develop solutions utilizing Azure storage, and more.
In this quickstart, create a Node.js app with Azure App Configuration to centralize storage and management of application settings separate from your code.
Learn how to use Azure App Configuration, a managed service that helps developers centralize their application and feature settings simply and securely.