Overview
This tutorial shows you how to rotate a secret stored in Azure Key Vault using the @azure/keyvault-secrets package for JavaScript/Node.js.
Secret rotation is a best‑practice for security. The steps include retrieving the current secret, creating a new version, and optionally disabling the old version.
Prerequisites
- Node.js >=14
- An Azure subscription
- A Key Vault instance with
get,set, anddeletepermissions for the app. - Azure CLI installed for authentication (or use Managed Identity).
Run the following command to install the SDK:
npm install @azure/identity @azure/keyvault-secrets
Setup
Authenticate using DefaultAzureCredential. This works locally (Azure CLI) and in Azure (Managed Identity).
import { DefaultAzureCredential } from "@azure/identity";
import { SecretClient } from "@azure/keyvault-secrets";
const credential = new DefaultAzureCredential();
const vaultUrl = "https://<YOUR-KEYVAULT-NAME>.vault.azure.net";
const client = new SecretClient(vaultUrl, credential);
Rotate the Secret
Below is a complete async function that rotates a secret to a new value.
async function rotateSecret(secretName, newValue) {
// 1. Get the latest version (optional, for audit)
const latest = await client.getSecret(secretName);
console.log(`Current version: ${latest.properties.version}`);
// 2. Set the new secret value – creates a new version automatically
const newSecret = await client.setSecret(secretName, newValue);
console.log(`New version created: ${newSecret.properties.version}`);
// 3. (Optional) Disable the previous version
await client.updateSecretProperties(latest.name, latest.properties.version, {
enabled: false
});
console.log(`Disabled old version: ${latest.properties.version}`);
}
// Example usage:
await rotateSecret("MyApiKey", "newSecretValue123!");
Run the script with node rotate.js (or embed in your application).
Cleanup (Optional)
If you want to remove all previous versions after rotation, you can purge them:
async function purgeOldVersions(secretName) {
const versions = client.listPropertiesOfSecretVersions(secretName);
for await (const version of versions) {
if (version.enabled === false) {
await client.beginDeleteSecret(secretName, { version: version.version });
console.log(`Deleted version: ${version.version}`);
}
}
}
// purgeOldVersions("MyApiKey");