Azure SDK Samples: Key Vault Secrets (JavaScript)

This page provides a sample JavaScript implementation for interacting with Azure Key Vault secrets using the Azure SDK for JavaScript.

Prerequisites

  • An Azure subscription.
  • An Azure Key Vault instance configured.
  • Node.js and npm installed.
  • The necessary Azure SDK packages installed:
    npm install @azure/keyvault-secrets @azure/identity

Setting up Authentication

The following code demonstrates how to authenticate using DefaultAzureCredential, which tries multiple credential types (environment variables, managed identity, etc.). For local development, setting environment variables like AZURE_TENANT_ID, AZURE_CLIENT_ID, and AZURE_CLIENT_SECRET is common.


const { SecretClient } = require("@azure/keyvault-secrets");
const { DefaultAzureCredential } = require("@azure/identity");

// Replace with your Key Vault URL
const vaultUrl = "https://your-keyvault-name.vault.azure.net";

// Create a client that will authenticate through AAD
const client = new SecretClient(vaultUrl, new DefaultAzureCredential());

Creating or Updating a Secret

This example shows how to set a new secret or update an existing one.

// Function to set a secret
async function setSecret(secretName, secretValue) {
    try {
        const result = await client.setSecret(secretName, secretValue);
        console.log(`Secret '${secretName}' set successfully:`, result.value);
        return result;
    } catch (error) {
        console.error("Error setting secret:", error);
        throw error;
    }
}

// Example usage:
// setSecret("my-api-key", "supersecretapikey123");

Retrieving a Secret

Fetch the value of a secret from Key Vault.

// Function to get a secret
async function getSecret(secretName) {
    try {
        const secret = await client.getSecret(secretName);
        console.log(`Secret '${secretName}' retrieved successfully:`, secret.value);
        return secret.value;
    } catch (error) {
        console.error("Error getting secret:", error);
        throw error;
    }
}

// Example usage:
// getSecret("my-api-key");

Deleting a Secret

Schedule a secret for deletion. Note that for actual deletion, a separate recovery step is required if soft-delete is enabled.

// Function to delete a secret
async function deleteSecret(secretName) {
    try {
        const deletePoller = await client.beginDeleteSecret(secretName);
        console.log(`Secret '${secretName}' scheduled for deletion.`);
        // You can optionally wait for the deletion to complete if needed,
        // though it's often not necessary immediately.
        // await deletePoller.pollUntilDone();
        // console.log(`Secret '${secretName}' deleted.`);
        return deletePoller;
    } catch (error) {
        console.error("Error deleting secret:", error);
        throw error;
    }
}

// Example usage:
// deleteSecret("my-api-key");

Listing Secrets

Retrieve a list of all secrets within the Key Vault.

// Function to list all secrets
async function listSecrets() {
    try {
        console.log("Listing secrets:");
        for await of client.listPropertiesOfSecrets() {
            console.log(`- ${secret.name}`);
        }
    } catch (error) {
        console.error("Error listing secrets:", error);
        throw error;
    }
}

// Example usage:
// listSecrets();

Important Considerations

  • Permissions: Ensure the identity used by your application has the necessary permissions (e.g., "Get", "List", "Set", "Delete") on the Key Vault.
  • Error Handling: Implement robust error handling for network issues, permission errors, and Key Vault specific exceptions.
  • Security: Never hardcode secrets. Use Key Vault for all sensitive information.
  • Environment Variables: For local development, set the relevant Azure environment variables for DefaultAzureCredential.
  • Production: In production, use Managed Identities or Service Principals for secure authentication.

For more advanced scenarios and detailed API documentation, please refer to the official Azure Key Vault JavaScript documentation.