SecretsClient

The SecretsClient is the primary entry point for interacting with Azure Key Vault secrets. It allows you to create, retrieve, update, delete, and manage secrets stored in your Key Vault instance.

Instantiating SecretsClient

To use the SecretsClient, you first need to create an instance. This typically involves providing an endpoint to your Key Vault and an authentication credential.

import { DefaultAzureCredential } from "@azure/identity";
import { SecretsClient } from "@azure/keyvault-secrets";

// Replace with your Key Vault endpoint
const keyVaultName = "YOUR_KEY_VAULT_NAME";
const vaultUri = `https://${keyVaultName}.vault.azure.net`;

// Use DefaultAzureCredential for authentication
const credential = new DefaultAzureCredential();

// Create a new SecretsClient
const client = new SecretsClient(vaultUri, credential);

// Now you can use the 'client' object to perform operations
async function getSecretValue(secretName: string) {
    try {
        const secret = await client.getSecret(secretName);
        console.log("Secret value:", secret.value);
    } catch (error) {
        console.error("Error retrieving secret:", error);
    }
}

// Example usage
// getSecretValue("my-secret-name");

Key Methods

getSecret(secretName: string): Promise<SecretProperties>

Retrieves the latest version of a secret from Key Vault.

Note: This method returns a SecretProperties object which contains metadata about the secret. To get the actual secret value, you access the value property of the returned object.
// Example of retrieving a secret
async function retrieveSecret() {
    const secretName = "my-api-key";
    try {
        const result = await client.getSecret(secretName);
        console.log(`Secret Name: ${secretName}`);
        console.log(`Secret Value: ${result.value}`);
        console.log(`Secret ID: ${result.id}`);
    } catch (error) {
        console.error(`Error getting secret ${secretName}: `, error);
    }
}

setSecret(secretName: string, secretValue: string, options?: SetSecretOptions): Promise<SecretProperties>

Creates or updates a secret in Key Vault. If a secret with the same name already exists, its value will be updated.

// Example of setting a secret
async function createOrUpdateSecret() {
    const secretName = "my-new-config-secret";
    const secretValue = "ThisIsAHighlyConfidentialValue123!";
    try {
        const result = await client.setSecret(secretName, secretValue);
        console.log(`Secret ${secretName} created or updated successfully.`, result);
    } catch (error) {
        console.error(`Error setting secret ${secretName}: `, error);
    }
}

deleteSecret(secretName: string): Promise<DeletedSecretProperties>

Deletes a secret from Key Vault. The secret is soft-deleted and can be recovered within a retention period.

// Example of deleting a secret
async function removeSecret() {
    const secretName = "secret-to-delete";
    try {
        const result = await client.deleteSecret(secretName);
        console.log(`Secret ${secretName} deleted successfully.`, result);
        console.log(`Deletion Date: ${result.deletedDate}`);
    } catch (error) {
        console.error(`Error deleting secret ${secretName}: `, error);
    }
}

Common Options

Some methods accept optional configuration objects to customize behavior. These might include:

listPropertiesOfSecrets(): PagedAsyncIterableIterator<SecretProperties>

Lists all secrets in the Key Vault. This method returns an iterable iterator, allowing you to process secrets in batches.

// Example of listing secrets
async function listAllSecrets() {
    console.log("Listing secrets:");
    try {
        for await (const item of client.listPropertiesOfSecrets()) {
            console.log(`- ${item.name}`);
        }
    } catch (error) {
        console.error("Error listing secrets: ", error);
    }
}

Error Handling

When an operation fails, the SDK will throw an error. It's crucial to wrap your calls in try...catch blocks to handle potential issues gracefully. Common errors include:

Refer to the Azure Key Vault error codes for a comprehensive list of possible errors.


Last updated: October 26, 2023